Passing URL variables to a class based view

DisneylandSC picture DisneylandSC · Jan 17, 2017 · Viewed 7.5k times · Source

I have just started messing with class based views and I would like to be able to access variables from the URL inside my class. But I am having difficulties getting this to work. I saw some answers but they were all so short I found them to be of no help.

Basically I have a url

url(r'^(?P<journal_id>[0-9]+)/$',
    views.Journal_Article_List.as_view(), 
    name='Journal_Page'),

Then I would like to use ListView to display all articles in the particular journal. My article table however is linked to the journal table via a journal_id. So I end up doing the following

class Journal_Article_List(ListView):
    template_name = "journal_article_list.html"
    model = Articles
    queryset = Articles.objects.filter(JOURNAL_ID = journal_id)
    paginate_by = 12

    def get_context_data(self, **kwargs):
        context = super(Journal_Article_List, self).get_context_data(**kwargs)
        context['range'] = range(context["paginator"].num_pages)
        return context

The journal_id however is not passed on like it is in functional views. From what I could find on the topic I read I can access the variable using

self.kwargs['journal_id']

But I’m kind of lost on how I am supposed to do that. I have tried it directly within the class which lets me know that self does not exist or by overwriting get_queryset, in which case it tells me as_view() only accepts arguments that are already attributes of the class.

Answer

Alasdair picture Alasdair · Jan 18, 2017

If you override get_queryset, you can access journal_id from the URL in self.kwargs:

def get_queryset(self):
    return Articles.objects.filter(JOURNAL_ID=self.kwargs['journal_id'])

You can read more about django’s dynamic filtering in the docs.