How do I create list and detail views for django-taggit?
Asked Answered
A

1

8

I have a fairly simple model that uses Django Taggit for tagging.

Everything works great, but now I'd like to expand some functionality and I'm a little confused.

What I want is two views.

One that shows all my tags in the system. One that shows all the content from my app with a specific tag.

What makes sense to me is to do the following for each view.

in views.py for myapp

  1. All Tags

    from myapp.models import App

    from taggit.models import Tag

    class TagList(ListView):

    """ Get all the tags in the db """

    queryset = Tag.objects.all()
    template_name = "myapp/TagList.html"
    paginate_by = 10
    
  2. All content for a Tag

    from myapp.models import App

    from taggit.models import Tag

    class TaggedList(ListView): """ Get all the contet for a tag """

    template_name = "myapp/TaggedList.html"
    
    def get_object(self):
        return get_list_or_404(App, tag__iexact=self.kwargs['tag'])
    

Have I lost my mind or is it really that easy? BTW, I'm using generic class views.

Thanks for the help. Dave

Arethaarethusa answered 29/11, 2011 at 17:22 Comment(3)
ok, so the first one works great, and that is how I can do that.Arethaarethusa
The second one isn't work. I'm getting an integer error which tells me that I'm asking for the wrong thing.Arethaarethusa
return get_list_or_404(App, tags=self.kwargs['tag']) - that's the query I'm usingArethaarethusa
B
4

2. I believe this is for returning a single object, not multiple objects.

def get_object(self):  

Instead perhaps you should try something like the following:

def get_queryset(self):
    return TaggedItem.objects.filter(tag__iexact=self.kwargs['tag'])

This returns a list of items with GenericForeignKeys

If you are only interested in a specific model called App then

    return App.objects.filter(tags__name__in=[self.kwargs['tag']])

Default variable name in the template is TaggedItem_list then

{% for item in TaggedItem_list %}
   {{item.content_object}} {# generic foreign key here #}
{% endfor %}

The urls.py would have to be similar to

url(r'someapp/(?P<tag>\w+)/$', TaggedList.as_view())
Beabeach answered 8/12, 2011 at 5:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.