Django 快速实现登录功能,完成login_required验证

业务场景:某网站下很多站点URL,基于必须登录的页面下,首现会跳转到登陆页面进行登录,URL中明显记录了下一站点的路由,但实际登录后未进行跳转。

解决方案:利用django自带的认证方式,只需添加一个form和一个html即可。

总结:
整体实现方式是使用django自带的认证方式,加form表单(自己写的表单有些问题,各种msg处理都得重新写)。另外需区分admin登录页面与自定义的认证页面,我们引用admin页面的认证可以达到简化代码的操作,但是简单尝试调用发现并不可行。所以总归来说需要自己写一个登录页面,django帮我们认证,其他路由的认证只需要调用即可,并且在验证完成后跳转回访问的页面。

参考连接:
https://docs.djangoproject.com/en/3.1/topics/auth/default/#django.contrib.auth.views.LogoutView

具体步骤:

  1. project / urls.py:

    from django.contrib.auth.views import LoginView
    from django.contrib.auth.views import LogoutView
    from apt_main.forms import MyAuthenticationForm
    
    urlpatterns = [
    	path(r'accounts/login/', LoginView.as_view(template_name="login.html",authentication_form=MyAuthenticationForm), name='login'),
    	path(r'accounts/logout/', LogoutView.as_view(next_page="/account/login/"), name='logout'),  #根据参考连接修改重定向页面
    	...
    
  2. forms.py:

    from django.contrib.auth.forms import AuthenticationForm
    
    class MyAuthenticationForm(AuthenticationForm):
    	def __init__(self, *args, **kwargs):
    		super(MyAuthenticationForm, self).__init__(*args, **kwargs)
    		self.fields['username'].widget.attrs['placeholder'] = u'Username'
    		self.fields['password'].widget.attrs['placeholder'] = u'Password'
    
  3. login.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>登录</title>
    	<style>
    		h1 {
    			text-align: center;
    		}
    		form {
    			 400px;
    			margin: auto;
    		}
    </style>
    </head>
    <body>
    <h1>欢迎登录</h1>
    <form class="form-account" method="post">
    	{% csrf_token %}
    	{{ form.non_field_errors }}
    	{% for field in form %}
    		<div class="form-group form-inline{% if field.name != 'captcha' %} d-flex justify-content-between{% endif %}">
    			{{ field.label_tag }} {{ field }}
    			{% if field.help_text %}
    				<p class="help">{{ field.help_text|safe }}</p>
    			{% endif %}
    			<p>{{ field.errors }}</p>
    		</div>
    	{% endfor %}
    	<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
    </form>
    </body>
    </html>
    

    之后的页面中,若添加了@login_required,则将采用此页面进行登录

  4. views.py:

    @login_required()   #登陆用settings.py控制,登出用urls.py logout 控制
    def index(requests):
    	return HttpResponse("20000")
    
    ------------------class写法---------------------------
    
    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.views.generic import TemplateView
    
    class IndexViews(LoginRequiredMixin, TemplateView):
    	def get(self, request, *args, **kwargs):
    		return HttpResponse("2000")
    

    备注:
    LoginRequiredMixin等同于@login_required(login_url="/accounts/login/")。前者直接读取settings关于LOGIN_URL设置,该类内部应该也有相应的变量进行修改,后者默认也读取LOGIN_URL设置

  5. settings.py:

    LOGIN_URL = '/account/login/'
    LOGIN_REDIRECT_URL = '/'
    
原文地址:https://www.cnblogs.com/lisicn/p/14297637.html