URLconf与用于加载模板的URL模式不匹配

时间:2016-12-15 00:49:22

标签: python django url url-pattern

Python / Django初学者在这里。我遇到了这个错误:

  

使用learning_log.urls中定义的URLconf,Django尝试了这些URL   模式,按此顺序:

     
      
  1. ^管理员/

  2.   
  3. ^ $ [name =' index']

  4.   
  5. ^ topics / $ [name =' topic']

  6.   
  7. ^ topics /(?P \ d +)/ $ [name =' topic']

  8.         

    当前网址,主题/%网址' learning_logs:主题' 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 %}

这是我的views.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 Crash Course:我的教程中的实践,基于项目的编程简介。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:0)

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时,它会再次调用视图函数topics()吗?我认为它应该是topic(), 所以它应该是

    **# Detail page for a single topic
    url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic')**

答案 1 :(得分:0)

  

当前网址,主题/%网址'learning_logs:主题'topic.id%},   与这些中的任何一个都不匹配。

在您的模板中,您在“%”之前错过了“{” 它应该是 {%url'Learning_logs:topic'topic.id%}

答案 2 :(得分:-2)

您的命名空间定义为topic,因此不是

{% url 'learning_logs:topic' topic.id %}

使用

{% url 'topic' topic.id %}

答案 3 :(得分:-2)

就像这样

url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic')

此表达式出错:unbalanced parenthesis.