Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Check if connection is secure from template?

Tags:

ssl

django

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?

like image 778
mpen Avatar asked Dec 05 '10 19:12

mpen


4 Answers

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>
like image 130
Gabriel Grant Avatar answered Nov 13 '22 13:11

Gabriel Grant


I'm not sure if Google did this at the time I asked this question, but they now recommend you add the library via

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

The // will use whatever scheme you are currently using -- no extra code or conditionals required.

like image 7
mpen Avatar answered Nov 13 '22 15:11

mpen


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

like image 6
JAL Avatar answered Nov 13 '22 13:11

JAL


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

like image 1
Krystian Cybulski Avatar answered Nov 13 '22 15:11

Krystian Cybulski