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.

def baseurl(request):
    Return a BASE_URL template context for the current request.
    if request.is_secure():
        scheme = 'https://'
        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.

    # default context processors for Django 1.4
    # context processors for 'myproject'

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="">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