网页超链接的url不对
urls.py:
"""定义网站的url模式"""
from django.urls import path, re_path
from . import views
app_name = 'xxx'
urlpatterns = [
# 主页
path('', views.index, name='index'),
# 专题界面
path('topics/', views.topics, name='topics'),
# 特定专题的界面
re_path(r'^topics/(?P<topic_id>\d*)$', views.topic, name='topic')
]
views.py:
from django.shortcuts import render
from .models import Topic
# Create your views here.
def index(request):
"""主页"""
return render(request, 'xxx/index.html')
def topics(request):
"""专题界面"""
topics_ = Topic.objects.order_by('date_added')
context = {'topics': topics_}
return render(request, 'xxx/topics.html', context)
def topic(request, topic_id):
"""显示单个主题及其文章标题"""
topic_ = Topic.objects.get(id=topic_id)
blogs = topic_.blog_set.order_by('-date_added')
context = {'topic': topic_, 'blogs': blogs}
return render(request, 'xxx/topic.html', context)
base.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h2>
<a href="{% url 'xxx:index' %}">XXX</a>
-
<a href="{% url 'xxx:topics' %}">专题</a>
</h2>
{% block content %}{% endblock content %}
</body>
</html>
topics.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>专题</title>
</head>
<body>
{% extends 'xxx/base.html' %}
{% block content %}
<h4>所有专题:</h4>
<ul>
{% for t in topics %}
<li>
<a href="{% url 'xxx:topic' topic.id %}">{{ t }}</a>
</li>
{% empty %}
<li>您当前还没创建专题</li>
{% endfor %}
</ul>
{% endblock content %}
</body>
</html>
topic.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% extends 'xxx/base.html' %}
{% block content %}
<h4>专题: {{ topic }}</h4>
<h5>文章:</h5>
<ul>
{% for b in blogs %}
<li>
<p>{{ b.date_added|date:'Y.M.d H:i' }}</p>
<p>{{b.title|linebreaks}}</p>
</li>
{% empty %}
<li>您还没有创建这个专题的文章</li>
{% endfor %}
</ul>
{% endclock content %}
</body>
</html>
超链接指向的是原来的这个网页
能够跳转到显示单个专题的页面
最后我发现时topics.html出了问题
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>专题</title>
</head>
<body>
{% extends 'xxx/base.html' %}
{% block content %}
<h4>所有专题:</h4>
<ul>
{% for t in topics %}
<li>
<a href="{% url 'xxx:topic' t.id %}">{{ t }}</a>
</li>
{% empty %}
<li>您当前还没创建专题</li>
{% endfor %}
</ul>
{% endblock content %}
</body>
</html>
改成这样就行了