10π
You are passing an empty queryset to ModelFormset.
ExampleModelFormSet = modelformset_factory(ExampleModel, extra=2)
formset = ExampleModelFormSet(queryset=ExampleModel.objects.none(),
initial=[{'name': 'Some Name'},
{'name': 'Another Name'}])
which is indeed the way to achieve what you want. It makes sense to pass an empty queryset, else initial values will override the modelβs database value.
And if I suppose, you are passing a non-empty queryset, and yet want your extra forms to be filled will initial values, you can override the Formset
.
from django.forms.models import modelformset_factory
ExampleFormset = modelformset_factory(OpenIDProfile, extra=3)
class myFormset(ExampleFormset):
def _construct_form(self, i, **kwargs):
"""
Instantiates and returns the i-th form instance in a formset.
"""
if self.is_bound and i < self.initial_form_count():
pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name)
pk = self.data[pk_key]
pk_field = self.model._meta.pk
pk = pk_field.get_db_prep_lookup('exact', pk)
if isinstance(pk, list):
pk = pk[0]
kwargs['instance'] = self._existing_object(pk)
if i < self.initial_form_count() and not kwargs.get('instance'):
kwargs['instance'] = self.get_queryset()[i]
defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.data or self.files:
defaults['data'] = self.data
defaults['files'] = self.files
# Check to confirm we are not overwriting the database value.
if not i in range(self.initial_form_count()) and self.initial:
try:
defaults['initial'] = self.initial[i - self.initial_form_count()]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self.initial_form_count():
defaults['empty_permitted'] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
Note: initial
is list of dicts. Its desirable to have items in list exactly equal to the number of extra.
9π
New in Django 1.4 β¦if you set initial on a modelformset it now only applies to the βextraβ forms, not those bound to instances from the queryset:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#providing-initial-values
So the various hacks above are no longer necessary and using initial is the answer.
- [Django]-Save base64 image in django file field
- [Django]-How to create virtual env with python3
- [Django]-How can I iterate over ManyToManyField?
6π
The best way Iβve found to do this is to just manually adjust the formset objectβs βextraβ attribute after initialization. This has been tested and works in Django 1.9.
ExampleModelFormSet = modelformset_factory(ExampleModel, extra=1)
formset = ExampleModelFormSet(initial=[{'name': 'Some Name'},
{'name': 'Another Name'}])
formset.extra = 3
This will spit out 3 forms (2 prepopulated and 1 blank).
If you want something more dynamic (e.g. initial
is a var calculated somewhere else), you can do something like this:
ExampleModelFormSet = modelformset_factory(ExampleModel, extra=1)
formset = ExampleModelFormSet(initial=initial)
formset.extra += len(initial)
Hope that helps.
- [Django]-ModuleNotFoundError β No module named 'main' when attempting to start service
- [Django]-How to deploy an HTTPS-only site, with Django/nginx?
- [Django]-Difference between setattr and object manipulation in python/django
4π
It is still possible to pass initial to a ModelFormSet.
from django.forms.models import modelformset_factory
from example.models import ExampleModel
ExampleModelFormSet = modelformset_factory(ExampleModel)
formset = ExampleModelFormSet(initial=[{'name': 'Some Name'},
{'name': 'Another Name'}])
If this is not what your after, can you explain your question more.
EDIT:
ExampleModelFormSet = modelformset_factory(ExampleModel, extra=2)
formset = ExampleModelFormSet(queryset=ExampleModel.objects.none(),
initial=[{'name': 'Some Name'},
{'name': 'Another Name'}])
- [Django]-Setting Django up to use MySQL
- [Django]-How can I subtract or add 100 years to a datetime field in the database in Django?
- [Django]-Boto.exception.S3ResponseError: S3ResponseError: 403 Forbidden
1π
In Django 1.4 the rule changed: the number of initials to be displayed corresponds to βextraβ parameter.
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#providing-initial-values
In my case the count of initial parameters varies dynamically, so
I found the following way:
initial=[{'name': 'Some Name'},{'name': 'Another Name'}]
formset = ExampleModelFormSet(queryset=ExampleModel.objects.none(),
initial=initial, extra=len(initial))
class MyBaseFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
self.extra = kwargs.pop('extra', self.extra)
super(MyBaseFormSet, self).__init__(*args, **kwargs)
provided, ExampleModelFormSet is based on MyBaseFormSet
- [Django]-How to copy modules from one virtualenv to another
- [Django]-Django choices. How to set default option?
- [Django]-Django startswith on fields
0π
A simple solution could be that you pass a form that extends a modelform() to a formset (rather than modelformset).
That way you can set initial values in the form.
- [Django]-Django like framework for Java
- [Django]-Dynamic File Path in Django
- [Django]-Count number of records by date in Django
0π
I think you can use initial argument, as with regular formsets
http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset
- [Django]-Why does Django call it "views.py" instead of controller?
- [Django]-Accessing the object in a django admin template
- [Django]-Django prefetch_related id only
0π
You can alter the initial data afterwards.
For example:
# Construct the FormSet class
ExampleFormSet = modelformset_factory(ParentModel, ChildModel)
# Set the initial data
initial_data = {'field1': 1}
for form in ExampleFormSet.extra_forms:
for field in form.fields:
field.initial = initial_data[field.name]
- [Django]-How to filter empty or NULL names in a QuerySet?
- [Django]-How to automatically reload Django when files change?
- [Django]-Profiling Django
0π
The simple way how to pass initial data with the same count of extra forms:
MyModelFormSet = lambda *a, **kw: modelformset_factory(MyModel, extra=kw.pop('extra', 1))(*a, **kw)
Usage in views:
initial=[{'name': 'Some Name'},{'name': 'Another Name'}
formset = MyModelFormSet(queryset=MyModel.objects.none(), initial, extra=len(initial))})
- [Django]-Django "xxxxxx Object" display customization in admin action sidebar
- [Django]-How to read the database table name of a Model instance?
- [Django]-Django Admin β save_model method β How to detect if a field has changed?
0π
Affter two days found this: http://streamhacker.com/2010/03/01/django-model-formsets/
def custom_field_callback(field):
return field.formfield(required=False)
FormSet = modelformset_factory(model, formfield_callback=custom_field_callback)
def custom_field_callback(field):
if field.name == 'optional':
return field.formfield(required=False)
elif field.name == 'text':
return field.formfield(widget=Textarea)
elif field.name == 'integer':
return IntegerField()
else:
return field.formfield()
- [Django]-Django ModelForm with extra fields that are not in the model
- [Django]-Renaming an app with Django and South
- [Django]-Vagrant is not forwarding when I run django runserver on ssh