django project class notes - registration function

验证码生成源码:https://files.cnblogs.com/files/icewky/captcha.zip

First, the user model design

1, the user table field analysis

- 添加用户手机号字段
- 添加邮箱状态字段

2, user mode design

Django提供了`django.contrib.auth.models.AbstractUser`用户抽象模型类允许我们继承,扩展字段来使用Django认证系统的用户模型类。
要使用Django自带的user模型类,需要先导入`UserManager`包,创建新模型时继承它

User model class

from django.db import models
from django.contrib.auth.models import AbstractUser ,UserManager as _UserManager # 以防重名,映射一个新名字
# Create your models here.

class UserManager(_UserManager):
    '''
    重写用户管理器
    '''
    def create_superuser(self, username, password, email=None, **extra_fields):

        return super(self,UserManager).create_superuser(username=username,password=password,email=email,**extra_fields)

class Users(AbstractUser):
    '''
    重写用户模型,继承AbstractUser模型类
    '''
    objects = UserManager()
    # help_text在api接口文档中会用到

    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号码', error_messages={
        'unique':'此手机号已经注册'  # 指定报错的中文信息
    },help_text='手机号')
    email_as = models.BooleanField(default=False,verbose_name='邮箱状态')

    class Meta:
        db_table = 'tb_user'  # 指明数据库表名
        verbose_name = '用户'  # 在admin站点中显示的名称
        verbose_name_plural = verbose_name  # 显示的复数名称

    def __str__(self):  # 打印对象时调用
        return self.username

User model our custom class can not directly be identified Django authentication system, an authentication system using Django need to inform our custom model classes in the configuration file.
Set in the configuration file,
add the following configuration file in settings.py:

# 思考:为什么Django默认用户模型类是User?
# 阅读源代码:'django.conf.global_settings'
# AUTH_USER_MODEL = 'auth.User'
# AUTH_USER_MODEL = '应用名.模型类名'
# AUTH_USER_MODEL 参数的设置以点.来分隔,表示应用名.模型类名。
# 自定义用户模型
AUTH_USER_MODEL = 'user.Users'

Note: Django suggested that we set for AUTH_USER_MODEL parameters must be before the first database migration is set, otherwise unknown error may occur subsequent use.

Second, the implementation of migration

python manage.py makemigrations
python manage.py migrate

Note: If the migration when prompted to find users, please refer to: https://www.cnblogs.com/icewky/p/12364717.html

database

Third, the CAPTCHA

The pattern verification code generation tool captcha extract from the directory into utils
Note: captcha tools require a third package: pip install pillow
introduced captcha tool view files, according to their need to import the file path

from dj13.utils.captcha.captcha import captcha

Preparation of view:

from dj13.utils.captcha.captcha import captcha

def image_code(request):
    text,image = captcha.generate_captcha()

    return HttpResponse(content=image, content_type='image/jpg')

Add routes:

from . import views

# APP名字,用于解析路由地址,需在path中添加name属性
app_name = 'users'

# 路由设置
urlpatterns = [
    path('image_code',views.image_code,name='image_code'),
]

Access routes to see if normal:

Fourth, the pattern is added to the front end verification file

New js file
directory: static> js> register.js

$(function () {
    let $img =$('.form-item .captcha-graph-img img');
    genre();
    $img.click(genre);
    function genre() {
        image_code_uuid = generateUUID();
        let imageCodeUrl = '/image_code/' + image_code_uuid + '/';
        $img.attr('src',imageCodeUrl)
    }
     // 生成图片UUID验证码
   function generateUUID() {
    let d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
  }
})

Js file registration page introduction:

{% block script %}
    <script src="../../static/js/register.js"></script>
{% endblock %}

Modify the view file:

from django.http import HttpResponse
from dj13.utils.captcha.captcha import captcha
from django_redis import get_redis_connection  
# Create your views here.
import logging
logger = logging.getLogger('django')

def image_code(request,img_id):
    text,image = captcha.generate_captcha()
    redis_conn = get_redis_connection('verify_code')  # 连接Redis数据库
    # 保存 (键 过期时间 值)
    redis_conn.setex('img_{}'.format(img_id).encode('utf8'),300,text)
    logger.info('图形验证码是:{}'.format(text))

    return HttpResponse(content=image, content_type='image/jpg')

Modify the route, reception parameters

from . import views

# APP名字,用于解析路由地址,需在path中添加name属性
app_name = 'users'

# 路由设置
urlpatterns = [
    path('image_code/<uuid:img_id>/',views.image_code,name='image_code'),
]

final effect:


Guess you like

Origin www.cnblogs.com/icewky/p/12364048.html