Django: Accessing request in forms.py clean function

拜拜、爱过 提交于 2019-11-28 07:42:16

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!