Python/Django 初学者在这里。我遇到了这个错误:
使用learning_log.urls中定义的URLconf,Django尝试了这些URL 模式,按此顺序:
- ^管理员/
- ^$ [名称='索引']
- ^主题/$ [名称='主题']
- ^主题/(?P
\d+)/$ [name='主题']
当前 URL、topics/% url 'learning_logs:topic' topic.id %} 与其中任何一个都不匹配。
当我尝试加载我的主题模板时。这是我的模板:
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>Topic: {{ topic }}</p>
<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 %}
这是我的观点.py:
from django.shortcuts import render
from .models import Topic
def index(request):
'''The home page for Learning Log'''
return render(request, 'learning_logs/index.html')
def topics(request):
'''Show all topics.'''
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
def topic(request, topic_id):
'''Show a single topic and all its entries.'''
topic = Topic.objects.get(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 代码:
'''Defines URL patterns for learning_logs.'''
from django.conf.urls import url
from . import views
urlpatterns = [
# Home page
url(r'^$', views.index, name='index'),
# Show all topics.
url(r'^topics/$', views.topics, name='topics'),
# Detail page for a single topic
url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic')
]
我正在使用 Python 速成课程:基于项目的实践编程简介作为我的教程。
任何帮助将不胜感激。
在
urlpatterns = [
# Home page
url(r'^$', views.index, name='index'),
# Show all topics.
url(r'^topics/$', views.topics, name='topics'),
# Detail page for a single topic
url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic')
]
最后一个 url 详细说明它正在调用单个主题,您是在告诉它当 Django 找到与该模式匹配的 URL 时,它会再次调用视图函数 topic() 吗?我认为应该是topic(), 所以应该是
**# Detail page for a single topic
url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic')**
当前URL,topics/% url 'learning_logs:topic' topic.id %}, 与这些都不匹配。
在主题模板中,您在“%”之前漏掉了“{”。
应该是 {% url 'learning_logs:topic' topic.id %}
您的命名空间定义为
topic
,所以而不是
{% url 'learning_logs:topic' topic.id %}
使用
{% url 'topic' topic.id %}
会是这样的
url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic')
此表达式有错误:
unbalanced parenthesis.