Login

Add site info to request context

Author:
bthomas
Posted:
November 17, 2008
Language:
Python
Version:
1.0
Tags:
contextprocessor domain site
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. Absolute URL Templatetag by johnboxall 6 years, 2 months ago
  2. ScriptPrefixMiddleware by shellsage 5 years, 11 months ago
  3. Create short URL redirects for site urls. by matt.geek.nz 6 years, 5 months ago
  4. simple DomainsAliasMiddleware by matrix 6 years, 4 months ago
  5. template filter to include protocol and domain in absolute urls by czer 3 years 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.