[英]Django - form making one parent object and multiple child objects
I'm trying to make a Django model based form which will allow to create two models which one will be passed as a foreign key to second one.我正在尝试制作一个基于 Django model 的表单,该表单将允许创建两个模型,其中一个模型将作为外键传递给第二个模型。
models.py模型.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 forms
class IngredientForm(ModelForm):
class Meta:
model = Ingredient
fields = ['name', 'quantity']
class RecipeForm(ModelForm):
class Meta:
model = Recipe
fields = ['name']
and views.py ---- here is the problem和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)
part with inlineformset_factory, I made following docs: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#inline-formsets与 inlineformset_factory 一起,我制作了以下文档: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#inline-formsets
chapter: Using an inline formset in a view章节:在视图中使用内联表单集
but it does not work --> formset.is_valid() is returning False Where is the Issue?但它不起作用 --> formset.is_valid() 返回 False 问题出在哪里?
It seems like you could be missing the {{formset.management_form}}
in the HTML template.似乎您可能缺少 HTML 模板中的
{{formset.management_form}}
。
<form ...>
{{form...}}
{{formset..}}
{{formset.management_form}}
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.