Django ModelForms and request.user

Took a little bit of digging to figure this one out. If you’re using a ModelForm along with django.contrib.auth.models.User (or a customized User model), you’ll want to use the instance that is sitting in the request rather than allowing the ModelForm to create a new instance.

To do this, simply override the get_form_kwargs method in the view:

class MyView(UpdateView):
template_name = 'user.html'
form_class = UserForm
success_url = reverse_lazy('success')
def get_form_kwargs(self):
kwargs = super(MyView, self).get_form_kwargs()
kwargs['instance'] = self.request.user
return kwargs

view raw

hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s