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
- New Snippet! by Antoliny0919 4 days, 18 hours ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 3 weeks ago
- get_object_or_none by azwdevops 6 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 8 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 10 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.