一、完善用户注册
添加一条用户短信验证码数据之后进行验证。
user/views.py
class UserViewset(CreateModelMixin,viewsets.GenericViewSet): ''' 用户 ''' serializer_class = UserRegSerializer queryset = User.objects.all()
user/serializer.py添加
fields = ('username','code','mobile','password')
(2)password不能明文显示和加密保存
需要重载Create方法
#输入密码的时候不显示明文 password = serializers.CharField( style={'input_type': 'password'},label=True,write_only=True ) #密码加密保存 def create(self, validated_data): user = super(UserRegSerializer, self).create(validated_data=validated_data) user.set_password(validated_data["password"]) user.save() return user
这是重载Create方法,下面介绍如何用信号量来实现
信号量
(1)users下面创建signals.py
from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.contrib.auth import get_user_model User = get_user_model() # post_save:接收信号的方式 #sender: 接收信号的model @receiver(post_save, sender=User) def create_user(sender, instance=None, created=False, **kwargs): # 是否新建,因为update的时候也会进行post_save if created: password = instance.password #instance相当于user instance.set_password(password) instance.save()
(2)还需要重载配置
users/apps.py
from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' verbose_name = "用户管理" def ready(self): import users.signals
AppConfig自定义的函数,会在django启动时被运行
现在添加用户的时候,密码就会自动加密存储了