Question

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'


Well, I thought this would work without any problem, because Django's generic DetailView will look for "slug" or "pk" to fetch its object. However, navigating to "localhost/tag/RandomTag" gives me an error:

error:

ImproperlyConfigured at /tag/RandomTag/

TagDetailView is missing a queryset. Define TagDetailView.model, TagDetailView.queryset, or override TagDetailView.get_queryset().


Does anyone know why this is happening...???

Thanks!!!

Was it helpful?

Solution

because Django's generic DetailView will look for "slug" or "pk" to fetch its object

It will, but you haven't told it what model it is to use. The error is very clear about this:

Define TagDetailView.model, TagDetailView.queryset, or override TagDetailView.get_queryset().

You can use the model or queryset attributes to do this, or the get_queryset() method:

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():
        ....

There are a few different ways of telling the view where you want it to grab your object from, so have a read of the docs for more

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top