Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to URL parameter inside of get_queryset in Django?

Tags:

python

django

Supposing, I've got a URL pattern like this:

urlpatterns = [
    ...
    url(r'^mylist/(?P<offset>\d+)/$', MylistView.as_view(), name='mylist'),
    ...
]

My view class:

class MylistView(ListView):
    template_name = 'mylist.html'

    def get_queryset(self, *args, **kwargs):
        offset = ... # What should I type here?
        entries = models.MylistEntry.all()[offset:offset+10]
        return entries

How do I access to the URL parameter offset within the method get_queryset? I've checked the variables args and kwargs are empty.

Thanks for advance!

like image 628
Fomalhaut Avatar asked Jul 26 '17 15:07

Fomalhaut


People also ask

How do I get all query parameters in Django?

We can access the query params from the request in Django from the GET attribute of the request. To get the first or only value in a parameter simply use the get() method. To get the list of all values in a parameter use getlist() method.

How does Django treat a request URL string?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).


1 Answers

Use self of get_queryset method for fetch url parameter

 self.kwargs.get('offset')
like image 188
Neeraj Kumar Avatar answered Sep 29 '22 17:09

Neeraj Kumar