zoukankan      html  css  js  c++  java
  • 慕学在线网1.0_登录功能(2)

    1、在users的views.py中编写login的视图:

    from django.shortcuts import render
    from django.contrib.auth import authenticate,login
    
    # Create your views here.
    
    
    def user_login(request):
        if request.method == 'POST':
            # 获取用户提交的用户名和密码
            user_name = request.POST.get('username', None)
            pass_word = request.POST.get('password', None)
            # 成功返回user对象,失败None
            user = authenticate(username=user_name, password=pass_word)
            # 如果不是null说明验证成功
            if user is not None:
                # 登录
                login(request, user)
                return render(request, 'index.html')
            else:
                return render(request, 'login.html', {'msg': '用户名或密码错误'})
    
        elif request.method == 'GET':
            return render(request, 'login.html')
    

      
    2、修改login的路由,即url:

    3、更改login.html:

    4、修改首页index.html的右上角:当用户已登录时,显示用户姓名和图像及其个人中心信息; 如果没有登录,则显示登录和注册按钮:

      


    增加邮箱登录:

    5、继承ModelBackend类来做的验证,用自定义authenticate方法。

    from django.contrib.auth.backends import ModelBackend
    from .models import UserProfile
    from django.db.models import Q
    
    #邮箱和用户名都可以登录
    # 基础ModelBackend类,因为它有authenticate方法
    class CustomBackend(ModelBackend):
        def authenticate(self, request, username=None, password=None, **kwargs):
            try:
                # 不希望用户存在两个,get只能有一个。两个是get失败的一种原因 Q为使用并集查询
                user = UserProfile.objects.get(Q(username=username)|Q(email=username))
    
                # django的后台中密码加密:所以不能password==password
                # UserProfile继承的AbstractUser中有def check_password(self, raw_password):
                if user.check_password(password):
                    return user
            except Exception as e:
                return None
    

      
    6、MxOnline/settings.py添加如下代码:

    AUTHENTICATION_BACKENDS = (
        'users.views.CustomBackend',
    )
    

      


    用form实现登录

    7、把views中的user_login()函数改成基于类的形式,继承的View类:

    from django.views.generic.base import View
    
    class LoginView(View):
        def get(self,request):
            return render(request, 'login.html')
    
        def post(self,request):
            # 获取用户提交的用户名和密码
            user_name = request.POST.get('username', None)
            pass_word = request.POST.get('password', None)
            # 成功返回user对象,失败None
            user = authenticate(username=user_name, password=pass_word)
            # 如果不是null说明验证成功
            if user is not None:
                # 登录
                login(request, user)
                return render(request, 'index.html')
            else:
                return render(request, 'login.html', {'msg': '用户名或密码错误'})
    

      
    8、基于类的urls配置:

    from users.views import LoginView
    
      path('login/',LoginView.as_view(),name = 'login'),
    

      
    9、users下新建form.py文件:

    from django import forms
    
    # 登录表单验证
    class LoginForm(forms.Form):
        # 用户名密码不能为空
        username = forms.CharField(required=True)
        password = forms.CharField(required=True,min_length=5)
    

      
    10、定义好forms后利用它来做验证,并完善错误提示信息:

    from .forms import LoginForm
    
    class LoginView(View):
        def get(self,request):
            return render(request, 'login.html')
    
        def post(self,request):
            # 实例化
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                # 获取用户提交的用户名和密码
                user_name = request.POST.get('username', None)
                pass_word = request.POST.get('password', None)
                # 成功返回user对象,失败None
                user = authenticate(username=user_name, password=pass_word)
                # 如果不是null说明验证成功
                if user is not None:
                    # 登录
                    login(request, user)
                    return render(request, 'index.html')
                # 只有当用户名或密码不存在时,才返回错误信息到前端
                else:
                    return render(request, 'login.html', {'msg': '用户名或密码错误','login_form':login_form})
                
            # form.is_valid()已经判断不合法了,所以这里不需要再返回错误信息到前端了
            else:
                return render(request,'login.html',{'login_form':login_form})
    

      
    11、完善login.html地错误提示信息:

      
    12、当用户名为空,或者密码少于五位数时会出现如下提示:

    这就是form的作用
      
    未完待续~~~

    一个佛系的博客更新者,随手写写,看心情吧 (っ•̀ω•́)っ✎⁾⁾
  • 相关阅读:
    CodeForces979D:Kuro and GCD and XOR and SUM(Trie树&指针&Xor)
    HDU4188:RealPhobia (连分数的运用之一)
    从HDU2588:GCD 到 HDU5514:Frogs (欧拉公式)
    SPOJ:Eagle and Dogs(求树上每个点最远可以走到哪里---树的直径||DP)
    【字符串】BZOJ上面几个AC自动机求最为字串出现次数的题目
    codeforces round #405 B. Bear and Friendship Condition
    codeforces round #419 C. Karen and Game
    codeforces round #419 B. Karen and Coffee
    codeforces round #419 A. Karen and Morning
    【ZOJ 3609】Modular Inverse 最小乘法逆元
  • 原文地址:https://www.cnblogs.com/WoLykos/p/9722129.html
Copyright © 2011-2022 走看看