22-注册、登录、验证登录
验证登录
一、验证后端是否登录
1、在项目中的应用层文件夹下,创建一个名为utils的python package包,然后创建名为mixin_utils的py文件,文件的代码是:
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator class LoginRequiredMixin(object): """ 检查是否登录 """ @method_decorator(login_required(login_url="/login/")) def dispatch(self,request,*args,**kwargs): return super(LoginRequiredMixin, self).dispatch(request,*args,**kwargs)
2、在需要验证的应用view.py的视图层下,先导入验证登录的类,然后继承这个类:
from django.views.generic.base import View from utils.mixin_utils import LoginRequiredMixin class UserInfoView(LoginRequiredMixin,View): """ 用户个人信息,必须登录才能访问 """ def get(self,request): return render(request,"usercenter-info.html",{})
3、在应用层下配置好用户信息的url路径:
from django.conf.urls import url,include from .views import UserInfoView urlpatterns = [ #用户信息列表页 url(r'^info/$', UserInfoView.as_view(), name="user_info"), ]
4、在项目层下配置好路由
from django.conf.urls import url,include
urlpatterns = [ # 用户信息路由分发 url(r'^users/', include("users.urls", namespace="users")), ]
二、验证前端是否登录,如果登录根据不同逻辑展现不同信息:
{% if request.user.is_authenticated %} <div class="top"> <div class="wp"> <div class="fl"><p>服务电话:<b>33333333</b></p></div><div class="personal"> <dl class="user fr"> <dd>{{ request.user.nick_name }}<img class="down fr" src="/static/images/top_down.png"/></dd> <dt><img width="20" height="20" src="{{ MEDIA_URL }}{{ request.user.image }}"/></dt> </dl> <div class="userdetail"> <dl> <dt><img width="80" height="80" src="{{ MEDIA_URL }}{{ request.user.image }}"/></dt> <dd> <h2>用户名</h2> <p>{{ request.user.username }}</p> </dd> </dl> <div class="btn"> <a class="personcenter fl" href="{% url "users:user_info" %}">进入个人中心</a> <a class="fr" href="/logout/">退出</a> </div> </div> </div> </div> </div> {% else %} <div class="top"> <div class="wp"> <div class="fl"><p>服务电话:<b>33333333</b></p></div> <!--登录后跳转--> <a style="color:white" class="fr registerbtn" href="/register/">注册</a> <a style="color:white" class="fr loginbtn" href="/login/">登录</a> </div> </div> {% endif %}
三、注册和登录逻辑
1、路由分发
from django.conf.urls import url,include from users.views import LoginView,RegisterView urlpatterns = [
#登录路由 url(r'^login/$', LoginView.as_view(),name="login"),
#注册路由 url(r'^register/$', RegisterView.as_view(),name="register"), ]
在应用层users的视图view.py下的视图类:
from utils.email_send import send_register_email
from .models import UserProfile,EmailVerifyRecord
from .forms import LoginForm,RegisterForm
class RegisterView(View): def get(self,request): register_form = RegisterForm() return render(request, "register.html", {"register_form":register_form}) def post(self,request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get("email","") pass_word = request.POST.get("password","") if UserProfile.objects.get(email=user_name): return render(request, "register.html", {"msg": "此账号已经激活!","register_form":register_form}) user_profile = UserProfile() user_profile.is_active = False user_profile.username = user_name user_profile.email = user_name user_profile.password = make_password(pass_word) user_profile.save() send_register_email(user_name,"register") return render(request, "login.html") else: return render(request, "register.html",{"register_form":register_form}) 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", "") pass_word = request.POST.get("password", "") # 然后验证账号密码 user = authenticate(username=user_name, password=pass_word) if user is not None: if user.is_active: login(request, user) return render(request, "index.html") else: return render(request, "login.html",{"msg":"未激活状态!"}) else: return render(request, "login.html", {"msg": "用户名或密码错误!"}) else: return render(request, "login.html", {"login_form":login_form})
前端表单传到后端的字段要和后端匹配:
在应用users下的forms.py文件表单验证代码:
from django import forms from captcha.fields import CaptchaField from .models import UserProfile class LoginForm(forms.Form): username = forms.CharField(required=True,min_length=6) password = forms.CharField(required=True,min_length=6) class RegisterForm(forms.Form): email = forms.EmailField(required=True) password = forms.CharField(required=True,min_length=6) captcha = CaptchaField(error_messages={"invalid":u"验证码错误"})
在utils文件下的email_send.py的代码:
from random import Random from django.core.mail import send_mail from users.models import EmailVerifyRecord from MxOnline.settings import EMAIL_FROM def random_str(randomlength=8): str = "" chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789" length = len(chars)-1 random = Random() for i in range(randomlength): str += chars[random.randint(0,length)] return str def send_register_email(email,send_type="register"): email_record = EmailVerifyRecord() if send_type == "update_email": code = random_str(4) else: code = random_str(16) email_record.code = code email_record.email = email email_record.send_type = send_type email_record.save() send_title = "" send_body = "" if send_type == "register": send_title = "慕学在线网注册激活链接" send_body = "请点击下面链接激活你的账号:http://127.0.0.1:8000/active/{0}".format(code) send_status = send_mail(send_title,send_body,EMAIL_FROM,[email]) if send_status: pass elif send_type == "forget": send_title = "慕学在线网重置密码链接" send_body = "请点击下面链接重置你的密码:http://127.0.0.1:8000/reset/{0}".format(code) send_status = send_mail(send_title, send_body, EMAIL_FROM, [email]) if send_status: pass elif send_type == "update_email": send_title = "慕学在线网邮箱修改链接" send_body = "你的邮箱验证码为:{0}".format(code) send_status = send_mail(send_title, send_body, EMAIL_FROM, [email]) if send_status: pass
在项目设置文件中的邮箱设置代码:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.163.com" EMAIL_PORT = 25 EMAIL_HOST_USER = "mxonline123@163.com" EMAIL_HOST_PASSWORD = "lishuntao110" EMAIL_USE_TLS = False EMAIL_FROM = "mxonline123@163.com"