Zorgan
Zorgan

Reputation: 9123

I want to make a variable in my views.py which changes depending the name of the urlpattern used

Here's my code. whatever urlpattern is chosen: I want the name of it to be stored as url in views.py. Which is then used in queryset filter().

urls.py

url(r'^news/', BoxesView.as_view(), name='news'),
url(r'^sport/', BoxesView.as_view(), name='sport'),
url(r'^cars/', BoxesView.as_view(), name='cars'),

views.py

class BoxesView(ListView):
    url = #urlname to go here
    def get_queryset(self):
        queryset_list = Post.objects.all().filter(category=url)

models.py

category = models.CharField(choices=CATEGORY_CHOICES)

choices.py

CATEGORY_CHOICES = (
    ('1', 'news'),
    ('2', 'sport'),
    ('3', 'cars'),

)

Any idea?

Upvotes: 0

Views: 44

Answers (2)

damores
damores

Reputation: 2351

You can use this to get the name of the view

 url = resolve(self.request.path_info).url_name

UPDATE: Added "self." which is needed when using generic views. And don't forget to import:

 from django.core.urlresolvers import resolve

Upvotes: 0

ger.s.brett
ger.s.brett

Reputation: 3308

I would replace your url.py by something like this:

url(r'(?P<keyword>\w+)/$', BoxesView.as_view())

This changes your address into an url parameter which you can then access the in your methods like this:

def get_queryset(self):
            url = self.kwargs['keyword']
            queryset_list = Post.objects.all().filter(category=url)

Upvotes: 1

Related Questions