1👍
I don’t understand why you need to validate and save your main form before you instantiate the formsets. The usual thing to do is to instantiate all the forms first, then validate them all before saving anything. That way you can guarantee that the forms will only be saved if they all validate, and if any of them fail you’ll simply redisplay everything with the relevant errors.
0👍
I think your approach is ok, showing all this forms on one page, but maybe you don’t need formsets? .. I’m not completely sure, but if you just need 1 instance of each form in the page, maybe you don’t need formsets at all.
About the validation, just handle 3 different forms, and then on the save process, do all the save-management manually and before saving the main form (commit=False) you assign the multiple relationships.
Assuming M is for the main-model and A, B for the related models for which M has foreign keys to, then you could do it like this:
# views.py ...
def my_display_forms_view(request):
if request.method == 'POST':
m = M()
a = A()
b = B()
a_form = AForm(request.POST, instance=a)
b_form = BForm(request.POST, instance=b)
m_form = MForm(request.POST, instance=m)
if a_form.is_valid() and b_form.is_valid() and m_form.is_valid():
a = a_form.save()
b = b_form.save()
m = m_form.save(commit=False); # don't save it to db still
m.a = na
m.b = nb
m.save()
# eventually do some more stuff
else:
# generate new unbound forms here
a_form = AForm()
b_form = BForm()
m_form = MForm()
return render_to_response('template.html', {'m_form': m_form, 'a_form': a_form, 'b_form': b_form}, context_instance=RequestContext(request))
And then on your template:
{% if m_form and a_form and b_form %}
<form ... >
<!-- show main form here -->
<fieldset>
<!-- here the other forms -->
</fieldset>
</form>
{% endif %}
And that should be it.
- [Answer]-Using rest django rest framework for creating new object
- [Answer]-Record Total Value in Django
- [Answer]-Django exclude for same field with different values