Django formset set current user

前端 未结 5 1392
耶瑟儿~
耶瑟儿~ 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 08:58

    I rather to iterate forms directly in the view:

    for form in formset.forms:
        form.user = request.user
        formset.save()
    
    • It avoid creating unecessary BaseFormSet
    • It is cleaner
    0 讨论(0)
  • 2020-12-28 09:07

    Based on Paulo Cheque answer (which didn't really work for my case).

    I loved the idea of not writing a custom BaseFormSet inherited class.

    if formset.is_valid():
        new_instances = formset.save(commit=False)
        for new_instance in new_instances:
            new_instance.user = request.user
            new_instance.save()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-28 09:14

    Here is a similar question about passing form parameters to a formset:

    Django Passing Custom Form Parameters to Formset

    Personally, I like the second answer on there about building the form class dynamically in a function because it is very fast to implement and easy to understand.

    0 讨论(0)
提交回复
热议问题