[Django]-Can you check the internet protocol from Django's template?

50👍

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

40👍

Since Django 1.10, you can use:

request.scheme

in a view, or in a template:

{{ request.scheme }}

From the docs

A string representing the scheme of the request (http or https usually).

9👍

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 }}

2👍

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 deprecated SetRemoteAddrFromForwardedFor code as a starting point, if you go the custom middleware route.

Leave a comment