簡體   English   中英

提交帶有 POST 請求的表單后出現 ERROR 404

[英]ERROR 404 after submitting a form with POST request

http://127.0.0.1:8000/tasks工作正常,但是當我添加任務並提交時,我收到了 404,

錯誤:使用 mysite.urls 中定義的 URLconf,Django 按以下順序嘗試了這些 URL 模式:

admin/
polls/
newyear/
tasks/ [name='index']
tasks/ add [name='add']
The current path, tasks/{ % url 'add' % }, didn't match any 
of these

mysite\\tasks\\urls.py

from django.urls import path,include
from . import views


urlpatterns = [
path("", views.index, name='index'),
path("add", views.add, name='add')]

我的站點\\我的站點\\urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path('admin/', admin.site.urls),
path('polls/',include('polls.urls')),
path('newyear/', include('newyear.urls')),
path('tasks/', include('tasks.urls'))]

mysite\\tasks\\views.py

from django.shortcuts import render
tasks = ["foo", "bar", "baz"]
def index(request):
   return render(request, "tasks/index.html", { 
    "tasks": tasks
 })
  def add(request):
     return render(request, "tasks/add.html")
 
  )

mysite\\tasks\\templates\\tasks\\index.html

   {% extends "tasks/layout.html" %}

{% block body %}
<h1>
    Tasks
</h1>
   <ul>
    {%for task in tasks%}
        <li> {{task}}</li> 
    {%endfor%}

    </ul>
    <a href="{% url 'add' %}">Add a New Task</a>
  {% endblock %}

mysite\\tasks\\templates\\tasks\\add.html

{% extends "tasks/layout.html" %}

{% block body %}
<h1>
    Add Task
</h1>
<form action= "{ % url 'add' % }" method="post">
    <input type="text" name="task">
    <input type="submit">

</form>  
<a href= "{% url 'index' %}">View Tasks</a>
{% endblock %}

除了 Alexey Popov 用空格{% ... %}修復損壞的標簽的答案,還記得在你的表單中添加一個 csrf 令牌:

<form action= "{% url 'add' %}" method="post">
    {% csrf_token %}
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM