我正在创建一个应用程序,用户可以在其中按成分搜索食谱。我希望已登录的用户可以自己添加配方。我在使用ModelForm的地方创建了表格。现在我想在用户推送后将提交配方添加/保存到我可以在管理面板中看到的配方中,也可以进行搜索,但是现在看来无法保存新配方。 ..
我的代码在视图中:
def add_recipe(request):
if not request.user.is_authenticated:
return redirect('login_required')
add_recipe = RecipeForm(request.POST or None)
if add_recipe.is_valid():
print("your recipe has been added!")
add_recipe.save()
template = "drinks/add_recipe.html"
return render(request, template, {'RecipeForm': add_recipe})
我的表格:
from django.forms import ModelForm
from drinks.models import Recipe
class RecipeForm(ModelForm):
class Meta:
model = Recipe
fields = ['recipe_name', 'preparation', 'ingredients']
我的模板add_recipe:
<form method="post" action="">
{% csrf_token %}
<table>
{{RecipeForm}}
</table>
<input type="submit" value="Add recipe"/>
</form>
我的网址:
urlpatterns = [
path('', views.drink_list, name='drink_list'),
path('search/', views.search_results, name='search_results'),
path('no_name/', views.drink_list, name='drink_list'),
path('signup/', views.signup, name='signup'),
path('add_recipe/', views.add_recipe, name='add_recipe'),
path('login_required/', views.login_required, name='login_required'),
]
我不确定您要使用视图做什么(它们的名称不是很明确),但是您是否通过urls.py
文件注册了视图?
另外,action=""
您的模板不会执行任何操作。您需要指定网址以发送您的帖子请求!action
不应等于“”,而应等于您要提交表单的网址。就您而言,您应该action="{% url 'add_recipe' %}"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句