11

这可能是一个相当简单的问题,但我似乎无法从 Django Docs 中弄清楚。我正在尝试一次保存两个 ModelForm,其中一个是另一个的 ForeignKey。我不确定如何在视图中编写逻辑以确保它们正确地结合在一起。

模型.py

class Address(models.Model):
    address = models.CharField(max_length=100)
    city = models.CharField(max_length=50)
    zipcode = models.PositiveIntegerField()

class Store(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=140, blank=True)
    address = models.ForeignKey(Address, null=True)

表格.py

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

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

视图.py

@login_required
def create(request):
    if request.method == "POST":
        form1 = CreateStore1Form(request.POST)
        form2 = CreateStore2Form(request.POST)
        if form1.is_valid() and form2.is_valid():
            store = form1.save(address)
            new_address = form2.save(commit=False)
            new_address.store = store
            mew_address.save()
    else:
        form1 = CreateStore1Form()
        form2 = CreateStore2Form()
    return render(request, 'create.html', locals())

任何帮助,将不胜感激。谢谢!

4

1 回答 1

20

Django为这个用例提供了内联表单集:

内联表单集是模型表单集之上的一个小型抽象层。这些简化了通过外键处理相关对象的情况。

表格.py

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

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

视图.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())

另请参阅此问题以获取更多详细信息。

于 2012-07-24T21:42:30.103 回答