11 django form表单校验

Posted 栗子测试开发

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了11 django form表单校验相关的知识,希望对你有一定的参考价值。

1 编写form校验(form同model中字段命名一致)

from django import forms


class UserForm(forms.Form):
    username = forms.CharField(min_length=4,
                               max_length=11,
                               required=True,
                               error_messages={\'required\': \'用户名不能为空\'})
    password = forms.CharField(min_length=4,
                               max_length=50,
                               required=True,
                               error_messages={\'required\': \'密码不能为空\'})

 

2 view中采用form检验

import hashlib
import json

from django.core import serializers
from django.http import JsonResponse

# Create your views here.
from django.views import View
from user.models import User
from utils.mytoken import make_token, login_check
from user.form import UserForm

class Login(View):
    def post(self, request):
        print(\'post login\')
        body = json.loads(request.body)  # 转字典
        # form 校验
        form = UserForm(body)
        if form.is_valid():
            username = body[\'username\']
            password = body[\'password\']
            users = User.objects.filter(username=username)  # 返回数组
            if users.count() == 0:
                result = {\'code\': -1, \'msg\': u\'用户名或密码错误啦!\'}
                return JsonResponse(result)
            user = users[0]
            m = hashlib.md5()
            m.update(password.encode())
            # 密码比对
            if m.hexdigest() != user.password:
                result = {\'code\': -1, \'msg\': u\'用户名或密码错误!\'}
                return JsonResponse(result)

            # 生成 token
            token = make_token(username)
            # encode的作用是将unicode编码的字符串编码成二进制数据
            # decode的作用是将二进制数据解码成unicode编码
            result = {\'code\': 1, \'data\': {\'token\': token}, \'msg\': u\'登录成功!\'}
            return JsonResponse(result)
        else:
            print(form.errors)
            result = {\'code\': -1, \'msg\': \'参数错误\'}
            return JsonResponse(result)

 

3 参考

https://blog.csdn.net/qq_34755081/article/details/82822405

 

以上是关于11 django form表单校验的主要内容,如果未能解决你的问题,请参考以下文章

django后台管理

Django框架form表单配合ajax注册

Django框架 之 form表单

Django 之 form表单

Django form表单

Django中Form表单之字段详解