Skip to main content
 首页 » 编程设计

python之使用 slug 访问 url 时在 Django 中出现 NoReverseMatch 错误

2025年05月04日31lyhabc

I am newbie on python Django. when following Django Tutorial, I have trouble with url for slug field. I'm using Python 2.7.3 and 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 访问 url 时出现上述错误。但是当我尝试使用 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"), 
    ) 

博客/模型.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%} 

谢谢。

请您参考如下方法:

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

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

通过在您的模板中打印或使用您的数据库客户端来仔细检查它们。