Getting self.request.user for form cleaning

24 views
Skip to first unread message

David

unread,
May 13, 2015, 10:24:29 AM5/13/15
to django...@googlegroups.com
Hi

I am using both FormMixin, and ListView.

When validating the form I need the users id. How can I get that into the form for cleaning? I am presuming somehow using get_form and then using the form's init to grab it, but am unsure of the syntax.

Any ideas?

Many thanks

def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
return self.get(request, *args, **kwargs)

David

unread,
May 13, 2015, 11:14:09 AM5/13/15
to django...@googlegroups.com
For anyone else needing this:

In form:

    def __init__(self, *args, **kwargs):
        self.creator = kwargs.pop('creator', None)

In view:

form = PostForm(request.POST, creator=self.request.user.pk)

Stephen J. Butler

unread,
May 13, 2015, 11:30:30 AM5/13/15
to django...@googlegroups.com
If you're using FormMixin then you can also override get_form_kwargs:

def get_form_kwargs(self):
kwargs = super(MyForm, self).get_form_kwargs()
kwargs['creator'] = self.request.user.pk
return kwargs

Then let FormMixin instantiate the form instance itself.
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/b839e5db-1d25-425e-8bbb-b8a05d501e74%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.

David

unread,
May 13, 2015, 12:03:24 PM5/13/15
to django...@googlegroups.com
Thank you for your reply. 

I had previously tried that, but must have had the syntax wrong. Am now using get_form_kwargs() as it looks nicer.
Reply all
Reply to author
Forward
0 new messages