使用drf視圖集對user增刪改查注意事項
view.py
class UserViewSet(ModelViewSet):
queryset = User.objects.all()
lookup_field = 'username'# 修改視圖集默認byid查詢
serializer_class = UserSerializer
Serializer.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','username','password','is_superuser','is_active','is_staff')
def update(self, instance, validated_data):
get_password = validated_data.get("password")
if get_password:
try:
instance.set_password(get_password)
validated_data.pop('password')
except:
pass
return super().update(instance, validated_data)
def create(self, validated_data):
# user = User.objects.create(**validated_data)
# user.set_password(validated_data.get("password"))
# user.save()
# create_user 可代替上面的創建數據設置密碼bong保存到數據庫
user = User.objects.create_user(**validated_data)
return user
這裡我並沒有寫對數據校驗,在更新數據修改密碼時需要調用set_password方法,在創建用戶(post)請求時調用create_user或自己create,set_password,save創建,此時表中的用戶名是加密後的,如果不這樣調用,則會密碼是明文,無法登陸
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)