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.
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
- How to insert a row of data to a table using Django's ORM
- Celery βbeat on Heroku vs Worker and Clock processes
- Django Queryset of related objects, after prefiltering on original model
- Use Django dumpdata to dump a subset of overall data?
- DateTimeField received a naive datetime
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()
- Why swagger raises unclear error β Django
- Logging formatters in django
- Make Django test case database visible to Celery
- Foreign Key to User model
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)
- What's the purpose of Django "deconstruct" model field function?
- Verbose_name for a model's method
- Django ORM β confusion about Router.allow_relation()
- How to change my django server time
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.
- How to activate the process queue in "django-background-tasks"
- Error loading MySQLdb module: No module named 'MySQLdb'
- Django Building a queryset with Q objects
- Generating single access token with Django OAuth2 Toolkit