我正在尝试在Django中使用url添加一个锚标签,如下所示:
layout.html
{% extends "tasks/layout.html" %}
{% block body %}
<h1>Tasks</h1>
<ul>
{% for task in tasks %}
<li>{{ task }}</li>
{% endfor %}
</ul>
<a href="{% url 'tasks:add' %}">Add Tasks</a>
{% endblock %}Views.py
from django.shortcuts import render
tasks = ["foo", "bar", "baz"]
# Create your views here.
def index(request):
return render(request, "tasks/index.html", {
"tasks": tasks
})
def add(request):
return render(request, "tasks/add.html")应用程序的urls.py
from django.urls import path
from . import views
app_name = "tasks"
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('hello/', include("hello.urls")),
path('newyear/', include("newyear.urls")),
path('tasks/', include("tasks.urls"))
]然而,当我使用url方法设置href时,我一直收到以下错误,但当我硬编码路径时却没有:
Error during template rendering
In template C:\Users\User\Desktop\Coding\CS50W\Week3-Django\lecture3\tasks\templates\tasks\layout.html, error at line 0
'set' object is not reversible
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <title>Tasks</title>
5 </head>
6 <body>
7 {% block body %}
8 {% endblock %}
9 </body>
10 </html>
Traceback Switch to copy-and-paste view
C:\Users\User\Desktop\Coding\CS50W\Week3-Django\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\User\Desktop\Coding\CS50W\Week3-Django\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
C:\Users\User\Desktop\Coding\CS50W\Week3-Django\lecture3\tasks\views.py, line 6, in index
return render(request, "tasks/index.html", { …
▶ Local vars有什么建议指出我可能做错了什么吗?
发布于 2021-06-08 12:30:17
在app/urls.py文件中,您提到了您的app_name标签,因此每当您编写URL重定向或html模板时都必须提及
layout.html
{% extends "tasks/layout.html" %}
{% block body %}
<h1>Tasks</h1>
<ul>
{% for task in tasks %}
<li>{{ task }}</li>
{% endfor %}
</ul>
<!--- i have made change here -->
<a href="{% url 'tasks:add' %}">Add Tasks</a>
{% endblock %}https://stackoverflow.com/questions/67879636
复制相似问题