Reputation: 217
I have two models and one form and one formsets so Formsets contains foreign of form and I want to save add id to formsets when saving both the forms and formsets.
model.py
class fmodel(models.Model):
name=models.TextField(blank=True,null=True)
class smodel(models.Model):
desc=models.TextField(blank=True,null=True)
n=models.ForeignKey(fmodel,null=True,blank=True,related_name='somemodel')
forms.py
class fmodelForm(forms.ModelForm):
name=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class': 'form-control'}))
class Meta:
model=fmodel
fields=['name']
smodelFormset=modelformset_factory(
smodel,
fields=('desc',),
extra=1,
widgets={
'desc':forms.TextInput(attrs={'class': 'u-form'})
}
)
template
<div>
<form role="form" action="//" enctype='multipart/form-data' method="post" id="form_sample_2" class="form-horizontal" novalidate="">{% csrf_token %}
<div class="row">
<div class="col-md-6" style="margin-bottom: 30px;">
<label> name : </label>
{{form.name}}
</div>
<div class="col-md-6" style="margin-bottom: 30px;">
{{ form1.management_form }}
{% for f in form1 %}
<label> desc : </label>
{{f.desc}}
{% endfor %}
</div>
</div>
<input type="submit" value="Save" />
</form>
</div>
views.py
form=fmodelForm(request.POST or None)
formset = smodelFormset(request.POST or None)
if form.is_valid():
form.save()
if formset.is_valid():
forms=formset.save(commit=False)
for f in forms:
#here I want to add id of previously added form
f.save()
Upvotes: 2
Views: 2385
Reputation: 217
Feeling so dumb now after solving my own question.
so here is the answer:
views.py
form=fmodelForm(request.POST or None)
formset = smodelFormset(request.POST or None)
#Just add
if request.method == 'POST':
if form.is_valid() and if formset.is_valid():
instance=form.save()
forms=formset.save(commit=False)
for f in forms:
f.foreignkey=instance.id
f.save()
Upvotes: 1
Reputation: 477686
A form.save()
returns the instance it has saved. We can then iterate over the forms, and for each form, set the .foreign_key
of the f.instance
to that instance:
if form.is_valid() and formset.is_valid():
instance = form.save()
instances = formset.save(commit=False)
for obj in instances:
obj.foreign_key = instance
obj.save()
You probably first want to validate both the form
and the formset
. Since if one of the two is invalid. It might be better not to save any data at all.
Upvotes: 2