1.

How to Get the Current URL Within a Django Template

Answer»

In the Django TEMPLATE, we can use the request PROCESSOR to get the URL.

If you WANT to request a variable in the template, make sure you add 'django.template.context_processors.request' in your 'context_processors' settings. Also, do not forget to add other context processors you used in your application.

Till Django 1.9 version, by default, it comes CONFIGURED. Default Template configuration is -

TEMPLATES = [     {         'BACKEND': 'django.template.backends.django.DjangoTemplates',         'DIRS': [],         'APP_DIRS': True,         'OPTIONS': {             'context_processors': [                 'django.template.context_processors.debug',                 'django.template.context_processors.request',                 'django.contrib.auth.context_processors.auth',                 'django.contrib.messages.context_processors.messages',             ],         },     }, ]

Use below line of code to get current path :

{{ request.path }}

Use below line of code to get current path with querystring:

  {{ request.get_full_path }}

Use below line of code get Domain, path and querystring:

  {{ request.build_absolute_uri }}

For EXAMPLE, suppose your URL is  http://127.0.0.1:8000/home/?q=test

  • request.path will give you output /home/
  • request.get_full_path will give you output /home/?q=test
  • request.build_absolute_uri will give you output http://127.0.0.1:8000/home/?q=test


Discussion

No Comment Found