models.py
class Tag(models.Model):
name = models.CharField(max_length=64, unique=True)
slug = models.SlugField(max_length=255, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Tag, self).save(*args, **kwargs)
urls.py
url(r'^tag/(?P<slug>[A-Za-z0-9_\-]+)/$', TagDetailView.as_view(), name='tag_detail'),
views.py
class TagDetailView(DetailView):
template_name = 'tag_detail_page.html'
context_object_name = 'tag'
好吧,我认为这不会有任何问题,因为Django的通用DetailView会查找"slug“或"pk”来获取它的对象。但是,导航到"localhost/tag/RandomTag“会给出一个错误:
错误:
ImproperlyConfigured at /tag/RandomTag/
TagDetailView is missing a queryset. Define TagDetailView.model, TagDetailView.queryset, or override TagDetailView.get_queryset().
有人知道为什么会这样吗?
谢谢!
发布于 2013-08-15 02:06:50
因为Django的泛型DetailView会查找“片段”或"pk“来获取它的对象
它会的,但是你还没有告诉它它要使用什么型号。这个错误是非常清楚的:
定义TagDetailView.model、TagDetailView.queryset或重写TagDetailView.get_queryset()。
您可以使用model
或queryset
属性来完成此操作,或者使用get_queryset()
方法:
class TagDetailView(...):
# The model that this view will display data for.Specifying model = Foo
# is effectively the same as specifying queryset = Foo.objects.all().
model = Tag
# A QuerySet that represents the objects. If provided,
# the value of queryset supersedes the value provided for model.
queryset = Tag.objects.all()
# Returns the queryset that will be used to retrieve the object that this
# view will display. By default, get_queryset() returns the value of the
# queryset attribute if it is set, otherwise it constructs a QuerySet by
# calling the all() method on the model attribute’s default manager.
def get_queryset():
....
有几种不同的方法可以告诉视图要从哪里获取对象,因此请阅读医生们以获得更多信息。
https://stackoverflow.com/questions/18250412
复制