所以我想根据序列化程序验证为不同的失败创建一个自定义消息。但我只能找到如何创建一个标准的自定义响应,只针对成功和失败。虽然我只想为失败的提示消息创建响应。在
我找到了其中一个帖子,但这不是我想要的错误代码 来源:Django Rest Framework custom response message
基本上,错误消息必须基于中的特定验证错误序列化程序.py在
这是我的密码
序列化程序.py
class UserCreate2Serializer(ModelSerializer):
email = EmailField(label='Email Address')
valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']
birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False)
class Meta:
model = MyUser
fields = ['username', 'password', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime', 'ethnicGroup']
extra_kwargs = {"password": {"write_only": True}}
def validate(self, data): # to validate if the user have been used
email = data['email']
user_queryset = MyUser.objects.filter(email=email)
if user_queryset.exists():
raise ValidationError("This user has already registered.")
return data
# Custom create function
def create(self, validated_data):
username = validated_data['username']
password = validated_data['password']
email = validated_data['email']
first_name = validated_data['first_name']
last_name = validated_data['last_name']
gender = validated_data['gender']
nric = validated_data['nric']
birthday = validated_data['birthday']
birthTime = validated_data['birthTime']
ethnicGroup = validated_data['ethnicGroup']
user_obj = MyUser(
username = username,
email = email,
first_name = first_name,
last_name = last_name,
gender = gender,
nric = nric,
birthday = birthday,
birthTime = birthTime,
ethnicGroup = ethnicGroup,
)
user_obj.set_password(password)
user_obj.save()
return validated_data
视图.py
^{pr2}$从序列化程序验证部分可以看到,如果电子邮件存在,它将给出一个错误消息,说明该用户已注册。用户名也是一样,但Django有自己的验证,因为它是内置的。在
错误消息是否可以这样: 如果使用用户名,而不是
"username": [
"A user with that username already exists."
]
为了这个
"promptmsg": [
"A user with that username already exists."
]
--已更新--
模型.py
class MyUser(AbstractUser):
userId = models.AutoField(primary_key=True)
gender = models.CharField(max_length=6, blank=True, null=True)
nric = models.CharField(max_length=9, blank=True, null=True)
birthday = models.DateField(blank=True, null=True)
birthTime = models.TimeField(blank=True, null=True)
ethnicGroup = models.CharField(max_length=30, blank=True, null=True)
def __str__(self):
return self.username
您可以在
serializer.errors
上得到这个错误列表,看看validation是如何工作的相关问题 更多 >
编程相关推荐