简介:
Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。
Django是一个开放源代码的Web应用框架,由Python写成。
Django遵守BSD版权,初次发布于2005年7月, 并于2008年9月发布了第一个正式版本1.0 。
Django采用了MVC的软件设计模式,即模型M,视图V和控制器C。
用户名密码登陆实现:
在apps.users下找到views.py文件:
以下代码重写了authenticate()方法,方便用户扩展功能,比如邮箱验证登陆等。
在setting.py中重载一个变量:
AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)
from django.contrib.auth import authenticate, loginfrom django.contrib.auth.backends import ModelBackendfrom django.db.models import Q# 继承View 实现基于类的用户登陆from django.views.generic.base import View from .models import UserProfile# 重写 authenticate 登陆验证方法class CustomBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): try: # 验证用户名或邮箱, Q提供了一个对象间的或(与&)运算 user=UserProfile.objects.get(Q(username=username) | Q(email=username)) # 后台密码为暗文,传入的密码为明文, 所以需要使用check_password()方法验证密码 if user.check_password(password): # 验证成功返回user对象 return user # 登陆失败返回None except Exception as e: return None
继承django.views.generic.base中的View类,根据method的不同,对应实现GET和POST的不同处理,一般POST为验证用户登陆,在此基础上还可以添加form处理,减少错误提交,减少对服务器的访问次数。
# 基于类实现用户登陆class LoginView(View): # 会根据 method 调用 post或者get方法 def get(self, request): # 如果method为 GET 重新返回登陆页面 return render(request, "login.html", {}) def post(self, request): # 验证每个字段是否合法 login_form = LoginForm(request.POST) # 对每个字段进行预处理,如果不合法,直接提示错误信息 pre_check = login_form.is_valid() # 如果合法 if pre_check: # 从POST中取出用户名和密码 user_name = request.POST.get("username", "") if UserProfile.objects.filter(email=user_name): return render(request, "register.html", {"register_form": register_form, "msg": "用户已经存在"}) pass_word = request.POST.get("password", "") # 此处为上面重写的authenticate方法 user = authenticate(username=user_name, password=pass_word) if user is not None: # 如果成功返回对象,失败返回None login(request, user) # 调用login方法登陆账号 return render(request, "index.html") else: # 登陆失败 return render(request, "login.html", {"msg":u"用户名或密码错误"}) else: # form验证失败,给出错误信息 return render(request, "login.html", {"login_form":login_form})
新闻热点
疑难解答