我想知道是否有人知道为什么DRF没有在错误消息中大写用户对象的首字母,并且有简单的方法来纠正此错误?
创建用户的错误消息:
{
"password": [
"This field is required."
],
"email": [
"user with this email already exists."
]
}
models.py
class User(AbstractBaseUser, PermissionsMixin):
created = models.DateTimeField(auto_now_add=True)
email = models.EmailField(max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
def __str__(self):
return self.email
serializers.py
class RegisterUserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ('id', 'password', 'email')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = models.User(email=validated_data['email'])
user.set_password(validated_data['password'])
user.save()
return user
views.py
class UserListView(generics.ListCreateAPIView):
queryset = User.objects.all()
def create(self, request, *args, **kwargs):
serializer = RegisterUserSerializer(data=request.data)
if serializer.is_valid():
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:3)
最简单的方法是
class User(AbstractBaseUser, PermissionsMixin):
created = models.DateTimeField(auto_now_add=True)
email = models.EmailField(max_length=255, unique=True,error_messages={
'unique': "User with this email already exists.",
},)
...
答案 1 :(得分:3)
回答您的问题:
为什么DRF没有将用户对象的首字母大写
如果未明确提供,则DRF会构造如下的唯一错误消息:
unique_error_message = unique_error_message % {
'model_name': model_field.model._meta.verbose_name,
'field_label': model_field.verbose_name
}
对于django的用户模型,详细名称为:
>>> from django.contrib.auth.models import User
>>> User.Meta.verbose_name
'user'