Отправка формы Django приводит к ошибке 404

Когда пользователь отправляет форму, я получаю следующую ошибку:

Page not found (404)
Request Method: csrfmiddlewaretoken=uaL0Ogej2bd0oSaNLXYwu1CxSPWz6mcs0PuXiwM2mpe01VecK5IVBK40xvqcFCJF&views=0&likes=0&slug=&name=do+do+ahadalfjkdas%3Bldfjksal%3B12321&submit=Create+CategoryPOST
Request URL:    http://127.0.0.1:8000/rango/add_category/rango/add_category/
Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order:

^$ [name='index']
^admin/
^rango/ ^$ [name='index']
^rango/ ^about/ [name='about']
^rango/ ^category/(?P<category_name_slug>[\w\-]+)/$ [name='show_category']
^rango/ ^page/(?P<page_name_slug>[\w\-]+)/$ [name='show_page']
^rango/ ^add_category/$ [name='add_category']
The current path, rango/add_category/rango/add_category/, didn't match any of these.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

Кажется, я дважды добавляю rango/add_category и не возвращаюсь к индексной странице. Но я не уверен, что я пропускаю.

Вот соответствующий шаблон:

<!-- created in c7 for form viewing-->

<!DOCTYPE html>
<html>
    <head>
        <title>Rango</title>
    </head>

    <body>
        <h1>Add a Category</h1>
        <div>
            <form id = "category_form" method = "post" action = "rango/add_category/">
                {% csrf_token %}
                {% for hidden in form.hidden_fields %}
                    {{hidden}}
                {% endfor %}
                {% for field in form.visible_fields %}
                    {{ field.errors }}
                    {{ field.help_text }}
                    {{ field }}
                {% endfor %}
                <input type = "submit" name = "submit" value = "Create Category" />
            </form>
        </div>
    </body>
</html>

И соответствующий файл форм:

#file added c7, forms 
from django import forms
from rango.models import Page, Category

class CategoryForm(forms.ModelForm):
    name = forms.CharField(max_length=128,
                        help_text = "Please enter the category name.")
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    slug = forms.CharField(widget=forms.HiddenInput(), required=False)

    #Inline class to provide additional info on the form
    class Meta:
        #provide an association b/t ModelForm and model
        model = Category
        fields = ('name',)

Соответствующий файл URL:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^about/', views.about, name='about'),
    #?P makes group to match the slug 
    url(r'^category/(?P<category_name_slug>[\w\-]+)/$',
    views.show_category, name='show_category'),
    #page slug added at ex at end of 6
    # not sure if needed, given index view ...
    url(r'^page/(?P<page_name_slug>[\w\-]+)/$',
    views.show_page, name='show_page'),
    #show page added in ex at end of 6
    #next added at c7 for forms
    #ordering may matter for processing of requests -- see official docs 
    url(r'^add_category/$', views.add_category, name='add_category')]

Соответствующий вид из представлений:

def add_category(request):
    form = CategoryForm()

    #HTTP Post? (that is, did user supply data?)
    if request.method == 'POST':
        form = CategoryForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            # could also give confirmation message if you wanted
            return index(request)

        else:
            print(form.errors)

    return render(request, 'rango/add_category.html', {'form': form})
# new template created

Заранее спасибо.

🤔 А знаете ли вы, что...
Python имеет множество фреймворков для веб-разработки, такие как Django и Flask.


1
678
1

Ответ:

Решено

Попробуйте изменить URL-адрес действия вашей формы

<form id = "category_form" method = "post" action = "{% url 'add_category' %}">

Для получения дополнительной информации, пожалуйста, прочитайте https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#url