[Solved]-Saving Django ModelForm with a ForeignKey

21👍

Django provides inline formsets for this use case:

Inline formsets is a small abstraction layer on top of model formsets.
These simplify the case of working with related objects via a foreign
key.

forms.py

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address

class StoreForm(forms.ModelForm):
    class Meta:
        model = Store
        exclude = ('address',)

views.py

from django.forms.models import inlineformset_factory

@login_required
def create(request):    
    AddressInlineFormSet = inlineformset_factory(Address, Store, form=AddressForm)

     if request.method == 'POST':
         storeForm = StoreForm(request.POST)

         if storeForm.is_valid():
             new_store = storeForm.save()
             addressInlineFormSet = AddressInlineFormSet(request.POST, request.FILES, instance=new_store)

             if addressInlineFormSet.is_valid():
                addressInlineFormSet.save()
                return HttpResponseRedirect(reverse('some_happy_customer_url'))

             else:
                classificationformset = ClassificationInlineFormSet(request.POST, request.FILES, instance=new_store)
     else:
          addressInlineFormSet = AddressInlineFormSet()
          storeForm = StoreForm()
     return render(request, 'create.html', locals())

Please see also this question for more details.

Leave a comment