Saving Django ModelForm with a ForeignKey

前端 未结 1 335
忘了有多久
忘了有多久 2020-12-29 12:51

This is probably a fairly simple question, but I can\'t seem to figure it out from the Django Docs. I\'m trying to save a two ModelForms at once with one being a ForeignKey

相关标签:
1条回答
  • 2020-12-29 13:32

    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.

    0 讨论(0)
提交回复
热议问题