2

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.

1
  • Can you share the url config for this view? Commented Mar 25, 2020 at 8:00

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What if I want to send the other urls(i.e. except the one that is called out) to the template to be shown as links on the UI? I can explicitly define the other urls and add them to a list and update the context with this list but that doesn't seems to be a good approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.