6

我需要一些帮助。

在我的models.py 中,我有一张Note 表格。我想用这个表做的是创建一个表单,用户可以在其中为特定客户在文本字段中输入一些注释。

模型.py

class Note(models.Model):
    client = models.ForeignKey(Client)
    datetime = models.DateTimeField(default=datetime.now)
    user  = models.ForeignKey(User)
    note = models.TextField()

    def __unicode__(self):
        return unicode(self.user)

现在,当用户输入注释时,他们应该看到注释文本字段。提交表单后,表单应自动将日期+时间保存为时间和日期。我似乎在使用用户字段。提交表单后,经过身份验证的用户应自动保存。我不确定你怎么能做到这一点。我还想自动保存客户端,以便您访问的客户页面(r'^clients/(?P<client_id>\d+)/$', views.get_client)从该客户端自动保存。

这是我在 forms.py 中写的

表格.py

class NoteForm(forms.ModelForm):
    class Meta:
        model = models.Note
        exclude = ('client','user','datetime')

这里也是我的观点。

视图.py

def add_notes(request, client_id):
    client = models.Client.objects.get(pk = client_id)
    notes = client.note_set.all()
    if request.method == 'POST':
        form = forms.NoteForm(request.POST)
        if form.is_valid():
            form.save(True)
            request.user.message_set.create(message = "Note is successfully added.")
            return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")
    else:
        form = forms.NoteForm()
    return render_to_response('note_form.html', {'form':form, 'client':client,'notes':notes}, context_instance = RequestContext(request))
4

3 回答 3

10
    if form.is_valid():
        note = form.save(commit=False)
        note.user = request.user
        note.client = client
        note.save()
于 2011-06-20T10:08:02.983 回答
7
class NoteForm(forms.ModelForm):
    class Meta:
        model = models.Note
        exclude = ('client','user','datetime')

    def __init__(self, client, user, *args, **kwargs):
        self.client = client
        self.user = user
        super(NoteForm, self).__init__(*args, **kwargs)

    def save(self):
        note = super(NoteForm, self).save(commit=False)
        note.user = self.user
        note.client = self.client
        note.save()
        return note

并认为:

form = forms.NoteForm(client, request.user, request.POST)
于 2011-06-20T10:07:11.043 回答
1

首先,对于您的模型:

datetime = models.DateTimeField(auto_now=True)

更好。

对于你现在的观点,我认为你应该写:

note = Note(client=client, user=request.user)
form = forms.NoteForm(instance=note)
于 2011-06-20T10:14:51.770 回答