Passing a user, request to forms

前端 未结 1 1408
独厮守ぢ
独厮守ぢ 2020-12-08 22:09

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.F         


        
相关标签:
1条回答
  • 2020-12-08 22:31

    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
    
    0 讨论(0)
提交回复
热议问题