简体   繁体   English

为什么我在Django的/ blog /处获得NoReverseMatch

[英]Why am I getting NoReverseMatch at /blog/ in Django

I am currently following the book "Django by Example" and at chapter 1: Building a blog application, I am getting the following error when I try to access 127.0.0.1:8000/blog/ 我目前正在阅读《 Django范例》一书,在第一章:构建博客应用程序中,尝试访问127.0.0.1:8000/blog/时遇到以下错误

NoReverseMatch at /blog/ / blog /中的NoReverseMatch

Reverse for 'post_detail' with arguments '(2017, '08', '03', 'new-title')' and keyword arguments '{}' not found. 反向使用参数'(2017,'08','03','new-title')'和关键字参数'{}'的'post_detail'。 1 pattern(s) tried: ['blog/(?P\\d{4})/(?P\\d{2})/(?P\\d{2})/^(?P[-\\w]+) /$'] 尝试了1个模式:['blog /(?P \\ d {4})/(?P \\ d {2})/(?P \\ d {2})/ ^(?P [-\\ w] +)/ $']

Here is my templates/blog/base.html file 这是我的templates / blog / base.html文件

{% load staticfiles %}

<!DOCTYPE html>

<html>
<head>
  <title>{% block title %} {% endblock %}</title>
  <link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
  <div id = "content">
    {% block content %}
    {% endblock %}
  </div>

  <div id = "sidebar">
    <h2> My Blog</h2>
      <p> This is my blog </p>
  </div>
</body>
</html>

and my templates/blog/post/list.html file 和我的template / blog / post / list.html文件

{% extends "blog/base.html" %}

{% block title %}My Blog {% endblock %}

{% block content %}
  <h1> My Blog </h1>
  {% for post in posts %}
    <h2>
      <a href="{{ post.get_absolute_url }}">
        {{ post.title }}
      </a>
    </h2>
    <p class="date">
      Published {{ post.publish }} by {{ post.author }}
    </p>

    {{ post.body|truncatewords:30|linebreaks }}
  {% endfor %}
{% endblock %}

I cannot seem to find what is wrong, so I would appreciate your assistance. 我似乎找不到什么错,因此,感谢您的协助。

In case it helps, I am using Django 1.8.6 and Python 3.6.2 with virtualenvwrapper on a Linux system. 如果有帮助,我在Linux系统上将Django 1.8.6和Python 3.6.2与virtualenvwrapper一起使用。

You have at least two errors in your regex. 您的正则表达式中至少有两个错误。

Firstly, you have a stray ^ before the final pattern. 首先,在最终模式之前有一个流浪^ That means "match from the beginning of the string", so putting it in the middle of the string will always fail. 这意味着“从字符串的开头开始匹配”,因此将其放在字符串的中间总是会失败。

Secondly, you have a space before the final slash. 其次,在最后的斜杠前还有一个空格。

What you are missing is a reverse url for "post_detail". 您缺少的是“ post_detail”的反向URL。 You need to have a url that has name with the value "post_detail". 您需要具有名称值为“ post_detail”的URL。

Add this to urls.py 将此添加到urls.py

url(r'^blog/(?P\d{4})/(?P\d{2})/(?P\d{2})/^(?P[-\w]+) /$'', views.post_detail, name='post_detail'),

your view should also accept regular expression like; 您的视图还应该接受正则表达式,例如;

def post_detail(request, pattern):
    ....
    return render(request, template, context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM