如果我想为用户提供使用 https://
登录网站的选项而不是 http://
,我最好让他们选择在我的 View 或模板中到达那里。
我想在我的登录页面上有“使用安全连接”链接 - 但是,如果不对 URL 进行硬编码,我该怎么做?
我希望能够做到:
{% url login_page %}
{% url login_page_https %}
并让他们指向
http://example.com/login
和 https://example.com/login
.我该怎么做?
最佳答案
{% url %}
标签只生成 URL 的路径部分,而不是主机部分。它只生成类似“/path/to/here”的东西(你需要做的就是“查看源代码”,你会看到这是 href
的全部内容)。如果您当前在 http://example.com 上,则由您的浏览器决定链接也应该在 http://example.com 内.因此,在模板中生成安全链接所需要做的就是:
<a href="https://example.com{% url blah %}">
如果您不想对域名进行硬编码(我不会),您可以使用 the Site object并让它看起来像:
<a href="https://{{ site.domain }}{% url blah %}">
或者如果你不想使用sites框架,你可以使用
request.get_host
:<a href="https://{{ request.get_host }}{% url blah %}">
关于Django - 使用 {% url %} 生成的链接 - 如何使它们安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1785596/