Django formset set current user

前端 未结 5 1393
耶瑟儿~
耶瑟儿~ 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:14

    I tried the solution of selfsimilar but the BaseFormSet didn't work in my Django 1.6.

    I followed the steps in: https://code.djangoproject.com/ticket/17478 and the way that worked for me is:

    class NewStudentFormSet(BaseFormSet):
            def __init__(self, *args, **kwargs):
                self.user = kwargs.pop('user',None)
                super(NewStudentFormSet, self).__init__(*args, **kwargs)
                for form in self.forms:
                    form.empty_permitted = False
    
            def _construct_forms(self):
                if hasattr(self,"_forms"):
                    return self._forms
                self._forms = []
                for i in xrange(self.total_form_count()):
                    self._forms.append(self._construct_form(i, user=self.user))
    
                return self._forms
    
            forms = property(_construct_forms)
    

提交回复
热议问题