提交表单时找不到Django网址

sshussain270

我很抱歉,如果这个问题很愚蠢,我是这个问题的新手。我正在创建Django Web应用程序。我在其中创建了一个表格。当我提交表单时,即使打开该表单时第一次加载相同的URL,它也会显示未找到“ URL”。这是什么让我感到困惑。这是我的代码:

#forms.py
class Recipe_ruleForm(forms.ModelForm):
    class Meta:
        model = Recipe_rule
        fields = ('content',)

#urls.py

    url(r"^create_recipe_rule/(?P<recipe_pk>[0-9]+)/$",views.create_recipe_rule, name="create_recipe_rule"),

#views.py
def create_recipe_rule(request, recipe_pk):
    form = Knowledgebase_ruleForm
    selected_recipe = Recipe.objects.get(pk = recipe_pk)
    if request.method == 'POST':
           form = Recipe_ruleForm(request.POST)
           if form.is_valid():
               #current_user = request.user
               data = form.cleaned_data
               recipe_rule_data=Recipe_rule.objects.create(recipe=selected_recipe, content=data['content'])
               recipe_rule_data.save()
               recipe_rule = Recipe_rule.objects.get(pk = recipe_rule_data.pk)
               recipe=selected_recipe
               recipe = Recipe.objects.get(pk = recipe.pk)
               return redirect('recipe_detail', pk=recipe.pk)
           else:
               messages.error(request, "Error")
    return render(request, 'create_recipe_rule.html' , {'form': form})

这是我提交表单时出现的错误:

找不到页面(404)请求方法:POST请求URL:http:// [ip_adress]:[port] / create_recipe_rule /

更新:

这是我的模板:

{% extends "account/base.html" %}

{% load i18n %}
{% load bootstrap %}

{% block body_class %}applications{% endblock %}

{% block head_title %}{% trans "Create recipe" %}{% endblock %}

{% block body %}




<form action="/create_recipe_rule/" method="post">
{% csrf_token  %}




<div class="form-group">
<label for="{{ form.content.label }}">{{ form.content.label }}:</label>
<textarea type="{{ form.content.type }}" name="{{ form.content.name }}" max_length="500" class="form-control" id="{{ form.content.id }}"></textarea>
</div>




     <input class="btn btn-default" type="submit" value="submit">
</form>
{% endblock %}
阿拉斯代尔

您有action="/create_recipe_rule/",缺少配方ID。

一种选择是简单地从表单中删除操作,然后您的浏览器会将请求提交到当前URL。

<form method="post">

如果确实要包括表单操作,则首先需要更新视图,以便它在模板上下文中包含配方ID。

return render(request, 'create_recipe_rule.html' , {'form': form, recipe_id: recipe_id })

然后,您可以更新表单操作以包含配方ID。

action="/create_recipe_rule/{{ recipe_id }}"

使用{% url %}标记是一个好习惯,这样就不会在模板中对URL进行硬编码:

action="{% url 'create_recipe_rule' recipe_id %}"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章