NoReverseMatch at / blog /

时间:2017-04-26 13:59:14

标签: python django

我正在关注“django by example” 我遇到了这个问题,但我不知道是什么原因造成的。

以下是错误页面:

NoReverseMatch at / blog / 使用参数'('','','')找不到'post_detail'的反转。尝试了1种模式:['博客/(?P \ d {4})/(?P \ d {2})/(?P \ d {2})/(?P [ - \ w] + )/ $']

请求方法: GET

请求网址: http://127.0.0.1:8000/blog/

Django版本: 1.11

异常类型: NoReverseMatch

异常值: 使用参数'('','','')找不到'post_detail'的反转。尝试了1种模式:['博客/(?P \ d {4})/(?P \ d {2})/(?P \ d {2})/(?P [ - \ w] + )/ $']

例外位置: E:\ workspace \ pycharm \ djangobyexample \ mysite \ env \ lib \ site-packages \ django \ urls \ resolvers.py in _reverse_with_prefix,第497行

Python可执行文件: E:\ workspace \ pycharm \ djangobyexample \ mysite \ env \ Scripts \ python.exe

Python版本: 3.5.2

Python路径: [ 'E:\工作空间\ pycharm \ djangobyexample \ mysite的',  'E:\工作空间\ pycharm \ djangobyexample \ mysite的\ ENV \脚本\ python35.zip',  'E:\工作空间\ pycharm \ djangobyexample \ mysite的\ ENV \的DLL',  'E:\工作空间\ pycharm \ djangobyexample \ mysite的\ ENV \ lib中',  'E:\工作空间\ pycharm \ djangobyexample \ mysite的\ ENV \脚本',  'C:\用户\理查德\应用程序数据\本地\程序\ python的\ python35 \ Lib文件',  'C:\用户\理查德\应用程序数据\本地\程序\ python的\ python35 \ DLL文件',  'E:\工作区\ pycharm \ djangobyexample \ mysite的\ ENV',  'E:\工作空间\ pycharm \ djangobyexample \ mysite的\ ENV \ lib中\站点包']

主要URLConfiguration

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]

博客/ url.py

from django.conf.urls import url
from . import views

urlpatterns = [
    # post views
    # url(r'^$', views.post_list, name='post_list'),
    url(r'^$', views.PostListView.as_view(), name='post_list'),
    url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',
        views.post_detail,
        name='post_detail'),
    #url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'),
]

views.py

from django.shortcuts import render, get_object_or_404
from .models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import EmailPostForm
from django.core.mail import send_mail


# Create your views here.

class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = 'posts'
    paginate_by = 3
    template_name = 'blog/post/list.html'



def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post,
                             status='published',
                             publish__year=year,
                             publish__month=month,
                             publish__day=day)
    return render(request, 'blog/post/detail.html', {'post': post})

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse


class PublishedManager(models.Manager):
    def get_query(self):
        return super(PublishedManager, self).get_query().filter(status='published')


class Post(models.Model):
    STATUS_CHOICES = {
        ('draft', 'Draft'),
        ('published', 'Published'),
    }
    title = models.CharField(max_length=250, primary_key=True)
    slug = models.SlugField(max_length=250, unique_for_date='publish')
    author = models.ForeignKey(User, related_name='blog_post')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

    class Meta:
        # Telling django to sort results by the publish field in descending order by default when we query the database
        ordering = ('-publish',)

    def __str__(self):
        return self.title

    objects = models.Manager()
    published = PublishedManager()

    def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.publish.year,
                                                 self.publish.strftime('%m'),
                                                 self.publish.strftime('%d'),
                                                 self.slug])

detail.html

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

{% block title %}{{ post.title }}{% endblock %}

{% block content %}
    <h1>{{ post.title }}</h1>
    <p class="date">
        Published {{ post.publish }} by {{ post.author }}
    </p>
    {{ post.body|linebreaks }}

{% endblock %}

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 %}
    {% include "pagination.html " with page=page_obj %}
{% endblock %}

base.html文件

{% load staticfiles %}

<html>
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>

</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>

1 个答案:

答案 0 :(得分:2)

这一行给出了错误,因为参数无效。

<!-- <a href="{% url 'blog:post_detail' post.year post.month post.day %}">-->

该帖子没有yearmonthday属性 - 它们是post.publish的属性。

您已在模板的下一行使用{{ post.get_absolute_url }}来获取网址。由于url标记行位于html注释<!-- -->中,因此最简单的修复方法是删除该行。