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
- Browser-native date input field by kytta 1 month, 1 week ago
- Generate and render HTML Table by LLyaudet 1 month, 2 weeks ago
- My firs Snippets by GutemaG 1 month, 2 weeks ago
- FileField having auto upload_to path by junaidmgithub 2 months, 3 weeks ago
- LazyPrimaryKeyRelatedField by LLyaudet 3 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.