Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a user, request to forms

How would I pass a user object or a request to my form for validation?

For example, I want to be able to do something like this --

class Form(forms.Form):
    ...
    def clean(self)
        user = request.user   # how to get request.user here?
        user = User           # how to pass the actual User object?

Thank you.

like image 224
David542 Avatar asked Jun 13 '11 00:06

David542


People also ask

How to pass request user in form Django?

Just pass it into the constructor and store it as an instance variable: class MyForm(forms. Form): def __init__(self, *args, **kwargs): self. request = kwargs.

How do you pass a user object into a class?

You need to pass the initial values in the view: views: def ContactsView(request): form_class = ContactForm(request=request, initial={'contact_name': request. user.


1 Answers

Just pass it into the constructor and store it as an instance variable:

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(MyForm, self).__init__(*args, **kwargs)

    def clean(self):
        print self.request.user
        ...

In your view:

form = MyForm(..., request=request)

And if using a class-based view (a CreateView in this example):

class MyCreateView(CreateView):

    ... 

    def get_form_kwargs(self):
        kwargs = super(MyCreateView, self).get_form_kwargs()
        kwargs.update({'request': self.request})
        return kwargs
like image 187
bradley.ayers Avatar answered Oct 14 '22 23:10

bradley.ayers