开发者

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

开发者 https://www.devze.com 2022-12-13 16:14 出处:网络
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:

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">
v开发者_JS百科ar 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?


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.


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).


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号