Elisha512 Elisha512 - 2 months ago 11x
Python Question

Django url not found upon submitting form

My apologies if the question is stupid, I am a newbie to this. I am creating a django web application. I have created a form inside it. When I submit the form, it says 'url' not found even though the same URL loads fine for the first time when opening the form. This is whats confusing me. Here is my code:

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


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

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 = Recipe_rule.objects.get(pk = recipe_rule_data.pk)
recipe = Recipe.objects.get(pk = recipe.pk)
return redirect('recipe_detail', pk=recipe.pk)
messages.error(request, "Error")
return render(request, 'create_recipe_rule.html' , {'form': form})

Here is the error when I submit the form:

Page not found (404) Request Method: POST Request
URL: http://[ip_adress]:[port]/create_recipe_rule/


Here is my template:

{% 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>

<input class="btn btn-default" type="submit" value="submit">
{% endblock %}


You have action="/create_recipe_rule/", which is missing the recipe id.

One option is to simply remove the action from the form, then your browser will submit the request to the current url.

<form method="post">

If you do want to include the form action, then first you need to update your view so that it includes the recipe id in the template context.

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

Then you can update the form action to include the recipe id.

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

It's good practice to use the {% url %} tag, so that you are not hardcoding urls in the template:

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