Passing URL variables to a class based view
Asked Answered
T

1

10

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.

Touchmenot answered 17/1, 2017 at 22:44 Comment(0)
S
19

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.

Semiweekly answered 17/1, 2017 at 23:8 Comment(2)
BTW, am I correct in understanding that .as_view() generates an instance of the class I define and that that is also the reason I can't access .self.kwargs in the main bit of the class because it describes the properties of the class and not a specific instance?Touchmenot
You can't access self.kwargs in class attributes because the class is loaded when the server starts, before the request has been made. As you say, as_view() returns the callable view used in the url config, but that happens after the class is loaded.Semiweekly

© 2022 - 2024 — McMap. All rights reserved.