A BASE_URL Template Variable in Django

Sometimes a Django template needs to reference the domain's base URL. Hard-coding the URL is obviously a bad idea. I like to use a context variable named BASE_URL in my templates. A simple context processor creates this variable based on the request.

context_processors.py
def baseurl(request):
    """
    Return a BASE_URL template context for the current request.
    """
    if request.is_secure():
        scheme = 'https://'
    else:
        scheme = 'http://'
        
    return {'BASE_URL': scheme + request.get_host(),}

The TEMPLATE_CONTEXT_PROCESSORS setting is used to add the new context processor. When adding this setting to settings.py, you must also include the default context processors for the version of Django.

settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    # default context processors for Django 1.4
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    # context processors for 'myproject'
    "myproject.context_processors.baseurl",
)

You can then use BASE_URL in Django templates.

  <a href="{{ BASE_URL }}">Home</a>

On the development server, the link will be rendered as:

  <a href="http://127.0.0.1:8000">Home</a>

And on a production server, the link would be rendered as:

  <a href="http://www.micahcarrick.com">Home</a>
Did you enjoy A BASE_URL Template Variable in Django? If you would like to help support my work, A donation of a buck or two would be very much appreciated.
blog comments powered by Disqus
Linux Servers on the Cloud IN MINUTES