我可能在一杯水中迷路了,但现在我想不通。我正在做一个餐厅顶点项目,客户可以看到菜单页面、购买页面,餐厅老板登录后可以管理并输入新的食谱,并创建他的个人菜单。我想做的是:当餐馆老板在输入食谱的地方提交POST请求时,我希望食谱也出现在菜单所在的页面上。通过这种方式可以更新新配方,也可以更改旧配方。(我复制模型、表格和视图代码以获得完整的概述(:
表格
class RecipeForm(forms.ModelForm):
class Meta:
model = Recipe
fields = '__all__'
型号.py
class Recipe(models.Model):
name = models.CharField(max_length=50)
ingredients = models.CharField(max_length=500)
def __str__(self):
return self.name
查看.py
def recipeEntry(request):
recipe_menu = Recipe.objects.all()
form = RecipeForm()
if request.method == 'POST':
form = RecipeForm(request.POST)
if form.is_valid():
form.save()
return redirect("recipe")
context = {'form':form, 'recipe_menu':recipe_menu}
return render(request, 'inventory/recipe.html', context)
recipe.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Recipe</title>
</head>
<body>
<form method="post", action="">{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Add Recipe">
</form>
{% for rec in recipe_menu %}
<div>
<p>Recipe: {{rec.name}}</p>
<p>Ingredient :{{rec.ingredients}}</p>
</div>
{% endfor %}
</body>
</html>
目前,提交POST请求的部分是有效的,所以这只是第二部分不起作用。我尝试了一些解决方案,但我不知道该怎么办。我还想为菜单页面创建一个GET视图,但我需要传递一个URL来获取数据,但我没有成功。
非常感谢你的帮助。
当它不是后请求时,您必须尝试显式实例化空表单:
def recipeEntry(request):
recipe_menu = Recipe.objects.all()
# form = RecipeForm() Not here yet
if request.method == 'POST':
# Instantiate form with request.POST
form = RecipeForm(request.POST)
if form.is_valid():
form.save()
return redirect("recipe")
else: # Explicitly write else block
# Instantiate empty form for get request
form = RecipeForm()
context = {'form':form, 'recipe_menu':recipe_menu}
return render(request, 'inventory/recipe.html', context)