(四)django-game:user view 编写

这里一篇写 注册 登录 用户激活 这三个功能

Captcha 包的使用 验证码 关于captfcha的使用 我新写了一篇 介绍简单的使用 这一篇 有点杂了

captcha使用:https://www.jianshu.com/p/a045ddae9144

首先 来 简单的 登录吧
LoginView
from django.shortcuts import render
from django.views import View
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.views import get_user_model
from django.contrib.auth.hashers import make_password
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from .models import UserProfile,EmailVerifyRecord
from .forms import LoginForm, RegisterForm
from utils.email_send import send_type_email

# 使用邮箱或用户名登录都行
class LoginView(View):
    def get(self, request):
        login_form = LoginForm()
        return render(request, "login.html", {'login_form': login_form})

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get('username', "")
            password = request.POST.get('password', "")
            user = authenticate(username=user_name, password=password) #验证用户
            if user is not None:    #如果有这个用户  就会取到这个用户的信息
                if user.is_active:    # 判断用户是否 激活
                    login(request, user)                
                    return HttpResponseRedirect(reverse('index'))
                else:
                    return render(request, 'login.html', {"msg": "用户未激活!"})
            else:
                return render(request, 'login.html', {"msg": "用户名或者密码错误!"})
        else:
            return render(request, 'login.html', {"login_form": login_form})
LoginForm 两个字段 一个用户名或邮箱 一个密码字段
class LoginForm(forms.Form):
    username = forms.CharField(required=True)
    password= forms.CharField(min_length=5,required=True)

这里还有一个 就是我们要修改 django自带的authenticated验证 它自带的 只能验证username字段 我们希望 用户使用email同样可以登录

所以 写一个 验证view
# 重写验证方法  他会自动来这里  使用这个验证方法
class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

就可以测试登录了 附上简单的html html太长了 就算了

ReigsterView
# 只能是用邮箱注册
class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm(request.POST)
        return render(request, 'register.html', {"register_form": register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_profile = UserProfile()
            user_name = request.POST.get('email', "")
            if UserProfile.objects.filter(username=user_name):
                return render(request, "register.html", {"register_form": register_form, "msg": "用户已经存在"})
            pass_word = request.POST.get('password', "")
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.password = make_password(pass_word)
            user_profile.is_active = False #默认为未激活
            user_profile.save()

            send_type_email(user_name, "register")   #发送 邮件  让用户激活
            return render(request, 'login.html', {})
        else:
            return render(request, "register.html", {"register_form": register_form})
RegisterForm 这里引入了一个新东西 第三方包 验证码的使用
class RegisterForm(forms.Form):
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True, min_length=5)
    captcha = CaptchaField(error_messages={"invalid": "验证码错误"})

关键来了 上面 注册时 需要给用户发送邮件 让用户激活

这里我们创一个 utils文件夹 来保存我们的 email_send.py 文件

# coding:utf-8
__author__ = "dfk"
__date__ = "2018/1/20 11:41"
from random import Random,choices
from django.core.mail import send_mail

from user.models import EmailVerifyRecord
from dj_game.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_type_email(email,send_type = 'register'):
    email_record  = EmailVerifyRecord()
    code = random_str(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.save()      #保存code 和  email 用于 激活 认证

    email_title =""
    email_body = ""

    if send_type == 'register':
        email_title = "小学生游戏网注册激活链接"
        email_body = "请点击下面的链接激活你的账户:http://127.0.0.1:8000/active/{0}".format(code)

        send_status = send_mail(email_title,email_body,EMAIL_FROM,[email])
        if send_status:
            pass

同样需要在settings中配置 email信息

#邮箱信息

EMAIL_HOST = "smtp.163.com"
EMAIL_PORT = 25
EMAIL_HOST_USER = "[email protected]"
EMAIL_HOST_PASSWORD = '你的授权码'   
EMAIL_USER_TLS = False
EMAIL_FROM = "[email protected]"

这样就可以测试注册了

既然 说到了 激活 所以我们还要写一个激活view来激活

激活 主要就是 发给用户 一个 带有code的链接 当用户 点击这个连接时,我们拿到这个code和 我们数据库中的email验证 如果相同 就 激活用户

# 激活
class ActiveUserView(View):
    def get(self, request, active_code):
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for record in all_records:
                email = record.email
                user = UserProfile.objects.get(email=email)
                user.is_active = True
                user.save()
        else:
            return render(request, 'active_fail.html')
        return render(request, 'login.html')

登出功能

LogouView
class LogoutView(View):
    def get(self, request):
        logout(request)
        return HttpResponseRedirect(reverse('index'))

注意配置urls 否则无法测试登录 注册功能

import xadmin
from django.conf.urls import url,include
from django.contrib import admin

from game.views import GamedetailView, GameIndexView, GamelistView
from user.views import LoginView, LogoutView, ActiveUserView, RegisterView

urlpatterns = [
    url(r'^xadmin/', xadmin.site.urls),
    #首页
    url(r'^$', GameIndexView.as_view(), name='index'),
    #游戏列表
    url(r'^gamelist/(?P.*)/$', GamelistView.as_view(), name='gamelist'),
    #游戏详情
    url(r'^games/(?P.*)/$', GamedetailView.as_view(), name='games'),
    #登录
    url(r'^login/$', LoginView.as_view(), name='login'),
    #注册
    url(r'^register/$', RegisterView.as_view(), name='register'),
    #退出
    url(r'^logout/$', LogoutView.as_view(), name='logout'),
    #激活
    url(r'^active/(?P.*)/$', ActiveUserView.as_view(), name='active'),
    #验证码相关url
    url(r'^captcha/', include('captcha.urls')),
]

你可能感兴趣的:((四)django-game:user view 编写)