views:

151

answers:

3

Right now, if I want to check whether the current page is accessed through http:// or https://, I will use the following Javascript in my templates and write html from document.write:

<script type="text/javascript">
var protocol = document.location.protocol;
if (protocol == "http:")
    document.write("regular");
else
    document.write("secured");
</script>

Is there another way to achieve the above in Django's template without using Javascript?

+5  A: 

if you use a RequestContext, you can do the following:

<p>You used: {% if request.is_secure %}HTTPS{% else %}HTTP{% endif %}

See the relevant part of the Django documentation.

jcdyer
+3  A: 

You need to enable the appropriate request context processor in your setting.py file:

TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.request',)

The template will now have a variable named request that contains the current HttpRequest. You can use it to find the protocol:

{{ request.is_secure }}
Jean-Philippe Goulet
+1  A: 

Try using RequestContext and request.is_secure in your template.

One caveat, the process of detecting HTTPS can differ from one server setup to the next so you may have to do a little work to get request.is_secure working. You can get it working either by ensuring that your front end / reverse proxy sets 'HTTP_X_FORWARDED_HOST' or by writing a middleware class that is custom to your setup.

Use the depricated[1] SetRemoteAddrFromForwardedFor code[2] as a starting point, if you go the custom middleware route.

(I am only allowed 1 link per post so please excuse the messed up links)

[1]: docs.djangoproject.com/en/dev/releases/1.1/#id1 "Django 1.1 release notes - Removed SetRemoteAddrFromForwardedFor middleware"

[2]: code.djangoproject.com/browser/django/trunk/django/middleware/http.py?rev=11000#L33 "SetRemoteAddrFromForwardedFor"

istruble