Django: Accessing request in forms.py clean function

后端 未结 2 936
無奈伤痛
無奈伤痛 2020-12-09 05:08

Hi Stackoverflow people,

In my clean function in forms.py, I would like to save automatically some information in a session variable. However, I do not seem to get

相关标签:
2条回答
  • 2020-12-09 05:44

    Overriding the form.get_initial() works for me

    class ItemCreate(FormView):
        def get_initial(self):
            init = super(ItemCreate, self).get_initial()
            init.update({'request':self.request})
            return init
    

    And in the clean we can access it with form.initial dict

    class sampleForm(forms.Form):
        ...
        ...
        def clean(self):
        user_request = self.initial['request']
    

    By the way, we don't need to pop the extra args like suggested above.

    0 讨论(0)
  • 2020-12-09 06:10

    You can overwrite the FormMixin's get_form_kwargs method to add the request for to the form's init parameters:

    class ItemCreate(FormView):
         def get_form_kwargs(self):
             kwargs = super(ItemCreate, self).get_form_kwargs()
             kwargs.update({
                 'request' : self.request
             })
             return kwargs
    
    0 讨论(0)
提交回复
热议问题