gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:31:00 24 4
gpt4 key购买 nike

我收到以下错误:

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 实例 的detailView 将显示与article 模型 具有外键关系的detail 模型的内容。这不是 article 实例的详细 View 显示该实例的传统方式。

此处的模板:

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

最佳答案

重写 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

关于django - 无法将关键字 u'slug' 解析为 Django 中的字段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23690364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com