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.
To add a URL variable to each link, go to the Advanced tab of the link editor. In the URL Variables field, you will enter a variable and value pair like so: variable=value. For example, let's say we are creating links for each store and manager.
Simply put, a URL parameter, according to Google, is a way to pass information about a click through a URL. Basically, that's what a URL parameter is. It's the evidence that a user made a specific click on a page that necessitated the creation of a parameter.
What Are URL Parameters? Also known by the aliases of query strings or URL variables, parameters are the portion of a URL that follows a question mark. They are comprised of a key and a value pair, separated by an equal sign. Multiple parameters can be added to a single page by using an ampersand.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With