Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.3 passing parameters to filter of class-based generic list view in url.py

Here's my code in url.py:

(r'^tag/(?P<tag>\w+)/$',
    ListView.as_view(
        model=List,
        context_object_name='some_list',
        queryset=List.objects.filter(tag__name__in=[tag_name]),
        template_name='some_list.html'))

I'd like to pass (?P<tag>\w+) to "tag_name" filter, but I don't know how to do it.

Also how can I pass multiple tags? Like this:

http://www.mysite.com/tag/tag1+tag2+tag3

url.py should get "tag1+tag2+tag3", split it into "tag1", "tag2" and "tag3", and then put them in "tag__name__in":

queryset=List.objects.filter(tag__name__in=[tag1, tag2, tag3])

Basically I'm confused by the class-based generic view. Any idea?

like image 823
devfeng Avatar asked May 27 '11 06:05

devfeng


1 Answers

You can overwrite the view's get_queryset method and construct a queryset with your results, eg.

from django.views.generic.list import ListView

class MyList(ListView):
    def get_queryset(self):
        tag_list = self.kwargs['tags'].split('+')
        return List.objects.filter(tag__name__in=tag_list)

# urls.py
...
url(r'tag/(?<tags>[\w\+]+)/', MyList.as_view())
like image 94
Bernhard Vallant Avatar answered Oct 19 '22 11:10

Bernhard Vallant