[英]Django - form making one parent object and multiple child objects
我正在嘗試制作一個基於 Django model 的表單,該表單將允許創建兩個模型,其中一個模型將作為外鍵傳遞給第二個模型。
模型.py
class Recipe(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Ingredient(models.Model):
name = models.CharField(max_length=200)
quantity = models.CharField(max_length=200)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
def __str__(self):
return self.name
forms
class IngredientForm(ModelForm):
class Meta:
model = Ingredient
fields = ['name', 'quantity']
class RecipeForm(ModelForm):
class Meta:
model = Recipe
fields = ['name']
和views.py ----這就是問題所在
def new_recipe_create_view(request, *args, **kwargs):
context = {}
created_recipe = None
form = RecipeForm()
if request.method == 'POST':
form = RecipeForm(request.POST)
if form.is_valid():
print("recipe successfully created")
form.save()
name = form.data['name']
created_recipe = Recipe.objects.filter(name=name).last()
#new recipe is being made correctly
IngredientFormSet = inlineformset_factory(Recipe, Ingredient, fields=('name', 'quantity'), extra=3, max_num=10, labels = {
'name': (''),
'quantity': (''),
})
if request.method == 'POST':
formset = IngredientFormSet(request.POST, instance=created_recipe)
if formset.is_valid():
formset.save()
else:
print("formset is not valid") # <------------------------------------------
else:
formset = IngredientFormSet( instance=created_recipe)
if form.is_valid() and formset.is_valid():
return redirect('index')
context['formset'] = formset
context['form'] = form
return render(request, 'recipes/create_recipe.html', context)
與 inlineformset_factory 一起,我制作了以下文檔: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#inline-formsets
章節:在視圖中使用內聯表單集
但它不起作用 --> formset.is_valid() 返回 False 問題出在哪里?
似乎您可能缺少 HTML 模板中的{{formset.management_form}}
。
<form ...>
{{form...}}
{{formset..}}
{{formset.management_form}}
</form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.