如何为这个Django视图强制使用HTTPS?

7 投票
1 回答
1662 浏览
提问于 2025-04-16 10:34
(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html', 'authentication_form':CustomAuthenticationForm}),

我该怎么给这个加上HTTPS的要求呢?我通常会用一个装饰器来处理这个问题……

但是在这种情况下,我不能这样做。

def secure_required(view_func):
    """Decorator makes sure URL is accessed over https."""
    def _wrapped_view_func(request, *args, **kwargs):
        if not request.is_secure():
            if getattr(settings, 'HTTPS_SUPPORT', True):
                request_url = request.build_absolute_uri(request.get_full_path())
                secure_url = request_url.replace('http://', 'https://')
                return HttpResponseRedirect(secure_url)
        return view_func(request, *args, **kwargs)
    return _wrapped_view_func

1 个回答

5

我觉得你可以这样把这个函数包裹起来:

from django.contrib.auth.views import login
from <<wherever>> import secure_required


urlpatterns = patterns('',
    (r'^login/?$',secure_required(login),{'template_name':'login.html', 'authentication_form':CustomAuthenticationForm}),
)

撰写回答