django模板标签url只有在空url模式最后出现时才有效



iam正在学习django,我不太明白这是django的行为还是iam做错了什么。因此,基本上我尝试使用django模板标记来创建一个固定的html页眉和页脚,以从中扩展base.html就像这个

<a href="{% url "index" %}" style="text-decoration:none;"><h1 style="text-align: center;color: green">Welcome to HireMe</h1></a>
{% block title %}
{% endblock title %}
{% block content %}
{% endblock content %}
<a href="{% url "about" %}" style="text-decoration:none;"><h4 style="text-align: left;color: purple;margin-top:256px;">About us</h4></a>

index.html就像这个

{% extends 'base.html' %}
{% block content %}
<body style="background-color: rgb(243,220,245) ">
<div align="center">
<p>Fugiat commodo officia laborum esse magna nisi commodo eu est non sunt in ut adipisicing nulla cupidatat dolor.</p>
<img src="https://media4.giphy.com/media/3pZipqyo1sqHDfJGtz/giphy.gif">
</div>
</body>
{% endblock content%}

并且当我在这里使用url模板标记href="{%url"index"%}";它应该带我去索引url模式中与我命名相关的页面

urlpatterns = [
path('admin/', admin.site.urls),
path('test/', include('pages.urls'), name='test'),
path('about', include('pages.urls'), name='about'),
path('', include('pages.urls'), name='index'),
]

并且只要"图案是最后一个,但如果我把线条改成这个

urlpatterns = [
path('admin/', admin.site.urls),
path('test/', include('pages.urls'), name='test'),
path('', include('pages.urls'), name='index'),
path('about', include('pages.urls'), name='about'), 
]

它需要我到/关于页面,如果我更改href="{%url"index"%}";到href="{%url"关于"%"}";这需要我去/aboubout页面,所以url值总是最后一个模式,或者我做了一些错误的

pages/url.py文件

from django.urls import path
from .views import HomePageView, AboutPageView, TestPageView
urlpatterns = [
path('about', AboutPageView.as_view(), name='about'),
path('test', TestPageView.as_view(), name='test'),
path('', HomePageView.as_view(), name='index'),
]

查看文件

from django.shortcuts import render
from django.views.generic import TemplateView
from django.http import HttpResponse
# Create your views here.

class HomePageView(TemplateView):
template_name = 'index.html'

class AboutPageView(TemplateView):
template_name = 'about.html'

class TestPageView(TemplateView):
template_name = 'test.html'

错误的来源是您缺少Django中URL处理的一些细节,有关它的更多细节:https://docs.djangoproject.com/en/3.2/topics/http/urls/

你的项目网址应该是这样的:

urlpatterns = [
path('admin/', admin.site.urls),
path('pages/', include('pages.urls')),
]

或者:

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')),
]

如果您不想在URL中使用前缀pages

和pages/urls.py:

from django.urls import path
from .views import HomePageView, AboutPageView, TestPageView
urlpatterns = [
path('', HomePageView.as_view(), name='index'),
path('about', AboutPageView.as_view(), name='about'),
path('test', TestPageView.as_view(), name='test'),
]

主页的url将是:<my_project_url>/pages/,关于页面:<my_project_url>/pages/about,依此类推

最新更新