Login

Add site info to request context

Author:
bthomas
Posted:
November 17, 2008
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

Sometimes you want to generate a really absolute URL, but the built-in url tag only generates a URL relative to the current domain. This context processor adds the extra information needed to the request context, so you can generate an absolute URL in a template like so:

{{ protocol }}://{{ domain }}{% url someview %}

This is similar to how the password reset email from contrib.auth generates the full URL in the email.

Save this somewhere as context_processors.py (or add to existing file if you have one), and add context_processors.site to your TEMPLATE_CONTEXT_PROCESSORS setting.

1
2
3
4
5
6
7
8
9
from django.contrib.sites.models import Site, RequestSite

def site(request):
    site_info = {'protocol': request.is_secure() and 'https' or 'http'}
    if Site._meta.installed:
        site_info['domain'] = Site.objects.get_current().domain
    else:
        site_info['domain'] = RequestSite(request).domain
    return site_info

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Archatas (on November 17, 2008):

The absolute url might also include a specific port. So that should be also included into the snippet.

#

Please login first before commenting.