1、完善用戶註冊django
添加一條用戶短信驗證碼數據以後進行驗證。app
user/views.py函數
class UserViewset(CreateModelMixin,viewsets.GenericViewSet): ''' 用戶 ''' serializer_class = UserRegSerializer queryset = User.objects.all()
user/serializer.py添加post
fields = ('username','code','mobile','password')
(2)password不能明文顯示和加密保存加密
須要重載Create方法spa
#輸入密碼的時候不顯示明文 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方法,下面介紹如何用信號量來實現rest
信號量code
(1)users下面建立signals.pyblog
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)還須要重載配置token
users/apps.py
from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' verbose_name = "用戶管理" def ready(self): import users.signals
AppConfig自定義的函數,會在django啓動時被運行
如今添加用戶的時候,密碼就會自動加密存儲了