我想为我的项目创建一个注册应用程序。 这是我的序列化器:
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth import get_user_model # If used custom user model
UserModel = get_user_model()
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name']
)
user.set_password(validated_data['password'])
return user
class Meta:
model = User
fields = ('id', 'username', 'password','email','first_name','last_name')
write_only_fields = ('password',)
read_only_fields = ('id',)
如您所见,我使用的是UserModel,它是rest_framework的默认模型之一。我想让我的注册序列化程序需要first_name字段。
等待你的帮助。
答案 0 :(得分:1)
您需要为required=True
字段指定first_name
attrubute:
class UserSerializer(serializers.ModelSerializer):
first_name = serializers.CharField(required=True)
password = serializers.CharField(write_only=True)