Dajngo tip: how to get the current URL within a Django template

This tip outlines a simple way to get the full URL for the current page in your Django template.

Make sure you have django.template.context_processors.request listed in your context_processors

Django 1.8 or above

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'project/templates/')],
        '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',
            ],
        },
    },
]

Django 1.7 or below

TEMPLATE_CONTEXT_PROCESSORS = (
    # ...
    'django.core.context_processors.request',
    # ...
)

Which makes {{ request }} available in your templates. Then in your template you can do

{{ request.build_absolute_uri }}
comments powered by Disqus