我可能迷失在一杯水中,但目前我無法弄清楚。我正在做一個餐廳頂點專案,客戶可以在其中看到選單頁面、購買頁面,登錄后餐廳的所有者可以管理和輸入新食譜并創建他的個人選單。我想要做的是:當餐廳老板提交一個 POST 請求并在其中輸入菜譜時,我希望菜譜也出現在選單所在的頁面中。通過這種方式可以更新新配方并更改舊配方。(我復制模型、表單和查看代碼以獲得完整概述):
表單.py
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)
食譜.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>
At the moment the part of submitting the POST request it works so is only the second part that don't works. I tried a bit few solution but i don't understand what to do. I thought also to create a GET view for the menu page but i need to pass an URL for get the data and i didn't works.
Thank you very much for the help.
uj5u.com熱心網友回復:
當它不是發布請求時,您必須嘗試顯式實體化空表單:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/358498.html
