How do I require HTTPS for this Django view?

2020-06-17 04:53发布

问题:

(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html', 'authentication_form':CustomAuthenticationForm}),

How do I add HTTPS required to this? I usually have a decorator for it..

But in this case I can't apply it.

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:

I believe you can wrap the function in this manner:

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