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
- Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
The absolute url might also include a specific port. So that should be also included into the snippet.
#
Please login first before commenting.