Saurabh
Saurabh

Reputation: 63

How to access url path in django view

How can I access the url in a Django view. I have a view handling following 5 urls:

localhost:8000/standings/
localhost:8000/standings/q1
localhost:8000/standings/q2
localhost:8000/standings/q3
localhost:8000/standings/q4

and my view is

class StandingsView(LoginRequiredMixin, TemplateView):
    template_name = 'standings.html'

Based on q1, q2, q3, q4 or None in the url path, I have to query data from the db and render to the given template.

Please suggest on how such scenarios can be handled.

Upvotes: 2

Views: 1141

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

You can access the path with self.request.path:

class StandingsView(LoginRequiredMixin, TemplateView):
    template_name = 'standings.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data()
        path = self.request.path
        # …
        return context

But processing the path might be cumbersome and error prone. You can define five urls here in the urls.py and inject values in the kwargs, like:

from django.urls import path

from app.views import StandingsView

urlpatterns = [
    path('standings/', StandingsView.as_view(), kwargs={'q': None}),
    path('standings/q1', StandingsView.as_view(), kwargs={'q': 1}),
    path('standings/q2', StandingsView.as_view(), kwargs={'q': 2}),
    path('standings/q3', StandingsView.as_view(), kwargs={'q': 3}),
    path('standings/q4', StandingsView.as_view(), kwargs={'q': 4})
]

Then you can access the added kwargs in self.kwargs['q']:

class StandingsView(LoginRequiredMixin, TemplateView):
    template_name = 'standings.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data()
        q = self.kwargs['q']
        # …
        return context

You might however want to take a look at a ListView [Django-doc] that can implement most of the boilerplate logic.

Upvotes: 4

Related Questions