使用slug访问url时,在Django中获取NoReverseMatch错误

时间:2015-03-29 20:49:32

标签: python django

  

我是python Django的新手。在关注Django Tutorial时,我   对于slug字段的url有问题。我使用的是Python 2.7.3和Django 1.7.6。

错误详细信息

Reverse for 'detail' with arguments '(u'',)' and keyword arguments
'{}' not found. 1 pattern(s) tried: [u'blog/(?P<slug>[\\w-]+)/$']

当我尝试使用slug访问网址时出现上述错误。但是当我尝试使用pk时,它工作正常,没有遇到任何错误。

源代码

miniblog / urls.py

urlpatterns = patterns('',
    url(r"^blog/", include("blog.urls", namespace="blog",app_name="blog")),)

博客/ urls.py

urlpatterns = patterns('',
    url(r"^(?P<slug>[\w-]+)/$",views.PostDetailView.as_view(), name="detail"),
    )

博客/ models.py

class Post(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, editable=False)#save the timestamp when the model first creatred and not the field is editable in admin
    updated_at = models.DateTimeField(auto_now=True, editable=False)
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255,blank=True,default='') #blank = True i.e it is not required for validatipn purpose , default = '' for not slug provided
    content = models.TextField()
    published = models.BooleanField(default=True)
    author = models.ForeignKey(User, related_name="posts")

    class Meta:
        ordering = ["-created_at", "title"]

    def __unicode__(self):
        return self.title

    def save(self, *args, ** kwargs):
        if not self.slug:
            self.slug = slugify(self.title) #title become the slug
        super(Post, self).save(*args,**kwargs)

博客/ views.py

class PublishedPostMixin(object):
    def get_queryset(self):
        queryset = super(PublishedPostMixin, self).get_queryset()
        return queryset.filter(published=True)

class PostDetailView(PublishedPostMixin,DetailView):
    model = Post

post_list.html

{% extends "_layouts/base.html" %}
{% load url from future %}
{% block page_title %}Blog posts | {%endblock%}
{% block page_content%}
<h2>Blog Posts</h2>
<ul>
    {% for post in post_list %}
        <li>
            <a href="{% url 'blog:detail' post.slug %}"> {{ post.title }}</a>
        </li>
    {% empty %}
    <li>
        Sorry, no posts yet. Check back soon!
    </li>
    {% endfor %}
</ul>
{%endblock%}

感谢。

1 个答案:

答案 0 :(得分:1)

错误表明您的post.slug之一是空的:

...with arguments '(u'',)' ...

通过在模板中打印或使用数据库客户端进行仔细检查。