'Django: Check if connection is secure from template?

I want to check if my site is running under HTTPS from within my template so that I can conditionally add S's to the HTTPs of my external javascript libraries (namely, jQuery). How can I do that?



Solution 1:[1]

If your resources are hosted on the same machine as you are serving requests from, it may not need to specify a url scheme at all:

<script src="/static/js/myfile.js" type="text/javascript"></script>

This will use the same protocol (http or https) and server as the request to the original page.

Edit 2 (2016):

If you're accessing a resource on another server, the best solution now (as pointed out by mpen below) is to use the relative URL scheme:

<script src="//media.example.com/static/js/myfile.js" type="text/javascript"></script>

This will automatically connect to the server using http or https depending on the connection to the current page.

Note that this may cause some problems if you need to support old browsers.

Edit: Alternatively, if you really need the info in your template for some reason, you can add the request context processor, and use a RequestContext in your views. This places a request variable in your template context, which gives you access to the HttpRequest object. You can then test if the request is secure by checking the value of request.is_secure

For example:

<script src="http{% if request.is_secure %}s{% endif %}://media.example.com/static/js/myfile.js" type="text/javascript"></script>

Solution 2:[2]

Check the request in the View with is_secure(), and send it to the template.

Solution 3:[3]

Please consider using the {% static %} template tag (in Django >= 1.4) which can be configured to host media files on a separate domain or server. This will do away with your is_secure problem.

https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:templatetag-staticfiles-static

Solution 4:[4]

for checking the connection scheme, you can use the request.scheme attribute

{% if request.scheme == "http" %}

{% elif request.scheme == "https" %}

{% endif %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 JAL
Solution 3 Krystian Cybulski
Solution 4 Al Mahdi