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?
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>
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.
Check the request in the View with is_secure(), and send it to the template.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With