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().
有谁知道为什么会这样...... ???
感谢!!!
答案 0 :(得分:4)
因为Django的通用DetailView会寻找“slug”或“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():
....
有几种不同的方法可以告诉视图您希望它从何处抓取您的对象,因此请阅读the docs了解更多