无法在Django中将关键字u'slug'解析为字段错误?

时间:2014-05-15 23:30:57

标签: django django-models django-views django-urls

我收到以下错误:

FieldError at /blog/1/first-post/

Cannot resolve keyword u'slug' into field. Choices are: article, date, id, likes

Request Method:     GET
Request URL:    http://127.0.0.1:8000/blog/1/first-post/
Django Version:     1.6.2
Exception Type:     FieldError
Exception Value:    

Cannot resolve keyword u'slug' into field. Choices are: article, date, id, likes

我的模特:

class Article(models.Model):
    title = models.CharField(max_length=20)
    body = models.TextField()
    image = models.ImageField(upload_to="/", blank=True, null=True)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.title)
        super(Article, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('article_detail', kwargs={'slug':self.slug, 'id':self.id})

    def __unicode__(self):
        return self.title

class Detail(models.Model):
    article = models.ForeignKey(Article)
    date = models.DateField()
    likes = models.IntegerField()

    def __unicode__(self):
        return "%s %s" % (self.article.title, self.likes)

    def get_absolute_url(self):
        return reverse('detail_article', kwargs={'id':self.id})

查看:

class ArticleDetail(DetailView):
     model = Detail
     template_name = "article_detail.html"
     context_object_name = "details"

     def get_queryset(self):
        print self.kwargs['slug']
        a = Article.objects.get(slug=self.kwargs['slug'])
        # print Details.object.get()
        # print Detail.objects.filter(article__slug=self.kwargs['slug']) fails with same error
        return Detail.objects.filter(article=a)

urls.py(这是博客应用程序内部):

urlpatterns = patterns('',

url(r'all$', ArticleList.as_view(), name='blog_all'),
url(r'^(?P<id>\d+)/(?P<slug>[-\w\d]+)/$', ArticleDetail.as_view(), name='article_detail'),
url(r'^detail/?(P<id?\d+)/$', DetailArticle.as_view(), name='detail_article'),
url(r'^create$', ArticleCreateView.as_view(), name='blog_create'),
)

基本上article instance的detailView将显示与detail具有外键关系的article model模型的内容。这不是article实例的详细视图显示该实例的传统方式。

这里的模板:

{% extends "base.html" %}
{% block content %}
{% for detail in details %}
<p>{{ detail.article.title }}</p>
<p>{{ detail.date }}</p>
<p>{{ detail.likes }}</p>
{% endfor %}
{% endblock %}

2 个答案:

答案 0 :(得分:5)

覆盖get_object(self, queryset=None)方法而不是DetailView get_queryset(self)是一种更简单的解决方案

class ArticleDetail(DetailView):
    model = Detail
    template_name = "article_detail.html"
    context_object_name = "details"

    def get_object(self, queryset=None):
        slug = self.kwargs['slug']
        a_obj = Article.objects.get(slug=slug)
        try:
           d_obj = Detail.objects.get(article=a_obj)
        except Detail.DoesNotExist:
            d_obj = None
        except Detail.MultipleObjectsReturned:
            #select the apt object
        return d_obj

答案 1 :(得分:4)

解决方案:您需要将url中的slug参数重命名为其他名称,或者在视图中将slug_url_kwarg重命名为其他值 - 而不是&#39; slug&#39;

说明: 当您添加到url时,django尝试通过slug获取对象,并且您的模型Detail没有slug字段。

链接到django代码:https://github.com/django/django/blob/master/django/views/generic/detail.py#L33

<强>更新

在SingleObjectMixin中

slug = self.kwargs.get(self.slug_url_kwarg, None)
...
elif slug is not None:
    slug_field = self.get_slug_field()
    queryset = queryset.filter(**{slug_field: slug})

所以django从你的url中获取slug,试图从Detail模型中获取slug字段并且失败

您的视图需要重写slug_url_kwarg属性:

class ArticleDetail(DetailView):
    model = Detail
    template_name = "article_detail.html"
    context_object_name = "details"
    slug_url_kwarg = "not_slug" # this attribute

 def get_queryset(self):
    print self.kwargs['slug']
    a = Article.objects.get(slug=self.kwargs['slug'])
    # print Details.object.get()
    # print Detail.objects.filter(article__slug=self.kwargs['slug']) fails with same error
    return Detail.objects.filter(article=a)

但我认为更好的方法是在您的网址中更改为属性:

url(r'^(?P<id>\d+)/(?P<article_slug>[-\w\d]+)/$', ArticleDetail.as_view(), name='article_detail'),

从视图kwargs

获取article_slug