[Django]-Django – How to pass a User object to a form in views.py

8πŸ‘

βœ…

I’m not sure what the point is of wanting to send it to the template. You have it in the view both before and after validation, after all: better to deal with it there.

The thing to do is to exclude the user field from the form definition, then set it manually on save:

class NoteForm(ModelForm):
   class Meta:
      model = Note
      exclude = ('user',)


if request.method == 'POST':
   model_form = NoteForm(request.POST, request.FILES)
   if model_form.is_valid():
       note = model_form.save(commit=True)
       note.user = request.user
       note.save()
       return...

Also note that your view never sends any validation errors to the template, and your template doesn’t show errors or the invalid values that the user has entered. Please follow the structure set out in the documentation.

2πŸ‘

You can extend the save method of the form,

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

Also your view must be in this structure:

from django.shortcuts import render
from django.http import HttpResponseRedirect

def contact(request):
     if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            # note: NoteForm.save(request.user)
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render(request, 'contact.html', {
        'form': form,
    })

(copied from https://docs.djangoproject.com/en/dev/topics/forms/)

πŸ‘€grgizem

0πŸ‘

πŸ‘€spicavigo

Leave a comment