本文介绍了使用ForeignKey保存Django ModelForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能是一个相当简单的问题,但我似乎无法从Django文档中得出结论。我试图一次保存两个ModelForms,一个是另一个的ForeignKey。我不知道如何在视图中写入逻辑,以确保这些逻辑正确合并。
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 of another. I'm not sure how to write the logic in the views to ensure these go together properly.
models.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)
forms.py
class CreateStore1Form(forms.ModelForm):
class Meta:
model = Store
exclude = ('address',)
class CreateStore2Form(forms.ModelForm):
class Meta:
model = Address
views.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())
任何帮助将不胜感激。谢谢!
Any help would be appreciated. Thanks!
推荐答案
Django提供。
这篇关于使用ForeignKey保存Django ModelForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!