Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 686
kender Avatar asked Nov 23 '09 20:11

kender


People also ask

What does form {% URL %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .

How can we handle URLs in Django?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).

How do I pass URL parameters in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

What is the difference between path and URL in Django?

The path function is contained with the django. urls module within the Django project code base. path is used for routing URLs to the appropriate view functions within a Django application using the URL dispatcher.


1 Answers

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 %}">
like image 181
Carl Meyer Avatar answered Oct 18 '22 17:10

Carl Meyer