我正在尝试使用api
创建一个用户。对于我的post/put
请求,我的密码未以加密格式保存。我的代码如下。
views.py
from urllib import request
from rest_framework import viewsets, status
from django.contrib.auth.models import User
from atest.serializers import UserSerializer
from rest_framework import permissions
from atest.permissions import IsOwnerOrReadOnly
from rest_framework.decorators import action
from rest_framework.response import Response
class UserViewSet(viewsets.ModelViewSet):
"""
This viewset provides operations on Users table to the same user.
"""
# permission_classes = [IsOwnerOrReadOnly,]
queryset = User.objects.all()
serializer_class = UserSerializer
serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
class UserSerializer(serializers.HyperlinkedModelSerializer):
password = serializers.CharField(max_length=128, style={'input_type': 'password'}, write_only=True)
class Meta:
model = User
fields = ('url', 'id', 'username', 'email', 'first_name', 'last_name', 'password')
def create(self, validated_data):
username = validated_data['username']
email = validated_data['email']
first_name = validated_data['first_name']
last_name = validated_data['last_name']
password = make_password(validated_data['password'])
def update(self, instance, validated_data):
instance.email = validated_data.get('email', instance.email)
instance.username = validated_data.get('username', instance.username)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.password = make_password(validated_data.get('password', instance.password))
instance.save()
return instance
请帮助我确定解决方案。我的密码未加密,我在做什么错了?
答案 0 :(得分:0)
您只是将事物分配给create
中的局部变量;另外,您不应该使用make_password
在update
中调用instance.password
;这样,您将在实例中重新散列哈希密码,使其无法使用。
此in the DRF documentation碰巧有一个示例(略为回旋处),可能会帮助您:
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'username', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User(
email=validated_data['email'],
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user