【发布时间】:2020-06-25 22:10:28
【问题描述】:
enter image description here我正在 Python Crash Course 中学习第 18 章 18.4.3,当我打开 http://localhost:8000/topics/1 时,我遇到了这个问题 - 没有主题与给定的查询匹配。 Django 3.0.7 和 python 3.8
views.py
from django.shortcuts import render,get_object_or_404
from .models import Topic
def index(request):
return render(request, 'learning_logs/index.html')
def topics(request):
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request,'learning_logs/topics.html',context)
def topic(request,topic_id):
topic = get_object_or_404(Topic,id=topic_id)
entries = Topic.entry_set.order_by('-date_added')
context={'topic':topic},{'entries':entries}
return render(request,'learning_logs/topic.html',context)
urls.py
app_name = 'learning_logs'
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('topics/',views.topics,name='topics'),
path('topics/<int:topic_id>/', views.topic, name='topic'),
]
topics.html
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>{{ topic }}</li>
<li>
<a href="{% url 'topic' topic_id %}">{{ topic }}</a>
</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}
topic.html
{% extends 'learning_logs/base.html' %}
{% block header %}
<h2>{{ topic }}</h2>
{% endblock header %}
{% block content %}
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>There are no entries for this topic yet.</li>
{% endfor %}
</ul>
{% endblock content %}
【问题讨论】: