[Fixed]-Django formset set current user

20πŸ‘

βœ…

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.

πŸ‘€selfsimilar

6πŸ‘

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
πŸ‘€Paulo Cheque

5πŸ‘

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()
πŸ‘€Andre Miras

2πŸ‘

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)
πŸ‘€EricPb

0πŸ‘

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.

πŸ‘€Spike

Leave a comment