Search code examples
pythondjangodjango-viewsdjango-generic-views

Accessing request object in django urls.py


The question is also inspired from documentation here.

I am using generic view (ListView) in Django in order to list out all the questions, current logged in user has asked. I was curious to do it without creating a View in views.py. So in urls.py I added a path like:

urlpatterns += [
    path('myqn/', login_required(views.ListView.as_view(model=models.Question, queryset=models.Question.objects.filter(user__id=request.user.id), template_name='testapp/question_list.html', context_object_name='questions')), name='myqn'),
]

Its giving me that:

NameError: name 'request' is not defined

I know it. Since, request object is passed by the URLConf to the View class/function. So, is there a way, I can access the user.id in this scope.

PS: The code works if I replace user__id=9. It lists out all the questions asked by user-9. :)


Solution

  • No, You can't.

    The as_view() accepts any class attributes of a view class. In your case, the request object will not accessible from the class

    class Foo(ListView):
        queryset = Question.objects.filter(user__id=request.user.id)

    The above snippet you can't reference the request and hence also in your urls.py

    In these kinds of complex situations, we should override the get_queryset(), as you know.