Login

Snippets by xlq

Snippet List

HTTPS redirections middleware with updated URL template tag

This middleware redirects HTTP requests to HTTPS for some specified URLs, in the same way as [85](http://djangosnippets.org/snippets/85/). It also changes the `url` template tag to use the `https` scheme for the same URLs. For example, if you have the following URL pattern: url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'https': True}) then the template: {% from future import url %} {% url 'django.contrib.auth.views.login' %} will render: https://host.example.com/accounts/login/ and any plain HTTP requests to /accounts/login get redirected to HTTPS. URL patterns not marked with `'https': True` remain unaffected. Notes: * The HttpRequest object must be present in the template context as `request`, so add `django.core.context_processors.request` to `TEMPLATE_CONTEXT_PROCESSORS` and make sure to use `RequestContext`. * This snippet overrides the existing `url` template tag. Remove the last line and register the new `url` function properly, as a separate tag, if this makes you unhappy. You'd then have to change your templates to use it. * It would be nicer to change the way reverse look-ups behave instead of changing only the `url` template tag, but the URL resolver, and the `reverse` function, know nothing about requests, so have no way to find the correct host name.

  • middleware
  • template
  • url
  • ssl
  • reverse
  • https
  • redirection
  • tls
Read More
Author: xlq
  • 0
  • 2

xlq has posted 1 snippet.