Django: Accessing request in forms.py clean function

后端 未结 2 945
無奈伤痛
無奈伤痛 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.

提交回复
热议问题