Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django forms want to auto-save user, client and datetime

I need some help.

In my models.py I have a table for Note. What I want to to do with this table is to create a form where a user could enter some notes in a text field for a particular client.

models.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)

Now when the user enters a note, they should only see the note text field. Once the form has been submitted the form should auto-save the date+time to what ever the time and date is. I seem to be having with the user field. Once the form has been submitted the authenticated user should be auto save. I am not really sure how you can do this. I also want to auto-save the client as well so who ever client's page you got to (r'^clients/(?P<client_id>\d+)/$', views.get_client), auto-save from that client.

Here is what I wrote in my forms.py

forms.py

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

And here my views as well.

Views.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))
like image 984
Shehzad009 Avatar asked Jun 20 '11 09:06

Shehzad009


1 Answers

    if form.is_valid():
        note = form.save(commit=False)
        note.user = request.user
        note.client = client
        note.save()
like image 76
Daniel Roseman Avatar answered Sep 18 '22 15:09

Daniel Roseman