1.完成路由接口的填写
2.完成视图代码的编写
from rest_framework.generics import CreateAPIView
from .models import User
from .serializers import UserModelSerializer
class UserAPIView(CreateAPIView):
"""用户注册"""
queryset = User.objects.all()
serializer_class = UserModelSerializer
3.完成序列化器代码的编写
from rest_framework import serializers
from .models import User
import re
class UserModelSerializer(serializers.ModelSerializer):
"""用户序列化器"""
sms = serializers.CharField(write_only=True, max_length=6, min_length=4, help_text="短信验证码")
token = serializers.CharField(read_only=True, min_length=1, help_text="jwt")
class Meta:
model = User
fields = ["id","username","token","password","mobile","sms"]
# 字段的额外声明
extra_kwargs = {
"id":{ "read_only": True, },
"username":{ "read_only": True, },
"password":{ "write_only": True, "min_length": 6, },
"mobile":{ "write_only": True, "min_length": 11 },
}
def validate(self, attrs):
mobile = attrs.get("mobile")
ret = re.match(r"1[3-9]d{9}$",mobile)
if not ret:
raise serializers.ValidationError("对不起,手机格式错误!")
try:
User.objects.get(mobile=mobile)
raise serializers.ValidationError("对不起,当前手机号已经被注册!")
except User.DoesNotExist:
pass
# todo 验证短信是否正确
return attrs ##返回值的作用是???
def create(self, validated_data):
mobile = validated_data.get("mobile")
password = validated_data.get("password")
username=mobile
try:
user = User.objects.create_user(username=username, password=password,mobile=mobile)
except:
raise serializers.ValidationError("创建用户失败!")
# 手动生成jwt
from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
user.token = jwt_encode_handler(payload)
return user