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

时间:2021-11-27 19:16:27

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.

我是python Django上的新手。在学习Django教程时,我对slug字段的url有问题。我使用的是Python 2.7.3和Django 1.7.6。

Error Details

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

Getting the above error when I try to access the url using slug. But when I tried with pk it worked fine, no error was encountered.

当我尝试使用slug访问url时获得上述错误。但是当我尝试用pk的时候,没有出现错误。

Source Code

miniblog/urls.py

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

blog/urls.py

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

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

blog/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%}

Thanks.

谢谢。

1 个解决方案

#1


1  

The error says that one of your post.slugs is empty:

错误显示了你的一个帖子。子弹是空的:

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

Double check them by printing in your template or using your database client.

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

#1


1  

The error says that one of your post.slugs is empty:

错误显示了你的一个帖子。子弹是空的:

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

Double check them by printing in your template or using your database client.

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