Django - links generated with {% url %} - how to make them secure?

django, https, url-routing

Solution

The `{% url %}` tag only generates the path portion of the URL, not the host portion. It only generates something like "/path/to/here" (all you need to do is "view source" and you'll see that's the entire contents of the `href`). It's your browser that assumes if you're currently on http://example.com the link should also be within http://example.com. So all you need to do to generate a secure link in your template is:

<a href="https://example.com{% url blah %}">

If you don't want to hardcode the domain name (and I wouldn't), you can use the Site object and have it look something like:

<a href="https://{{ site.domain }}{% url blah %}">

Or if you don't want to use the sites framework, you can use `request.get_host`:

<a href="https://{{ request.get_host }}{% url blah %}">

Problem

If I want to give an option for users to log in to a website using `https://` instead of `http://`, I'd best to give them an option to get there in my view or template. I'd like to have the link "Use secure connection" on my login page - but then, how do I do it without hardcoding the URL? I'd like to be able to just do: ``` {% url login_page %} {% url login_page_https %} ``` and have them point to `http://example.com/login` and `https://example.com/login`. How can I do this?

Original source