Django formset set current user

前端 未结 5 1391
耶瑟儿~
耶瑟儿~ 2020-12-28 08:18

Related to this question, but expanding on it - How would I use this technique in a formset?

I\'d like to use the current logged in user in a form, but I\'m using th

5条回答
  •  失恋的感觉
    2020-12-28 09:12

    By adding a class that extends BaseFormSet you can add custom code to pass a parameter to the form.

    in forms.py:

    class NewStudentFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            self.user = kwargs.pop('user', None)
            super(NewStudentFormSet, self).__init__(*args, **kwargs)
    
        def _construct_forms(self): 
            self.forms = []
            for i in xrange(self.total_form_count()):
                self.forms.append(self._construct_form(i, user=self.user))
    

    Then in views.py:

    # ...
    
    data = request.POST.copy()
    newStudentFormset = formset_factory(forms.NewStudentForm, formset=forms.NewStudentFormSet)
    formset = newStudentFormset(data, user=request.user)
    
    # ...
    

    Thanks to Ashok Raavi.

提交回复
热议问题