我以前在序列化器中验证模型的输入,但是不得不使用从AbstractUser
继承的属性更改为模型中的验证。
我认为我目前有以下内容:
class SetUserProfileView(generics.UpdateAPIView):
"""
Use this endpoint to change user profile.
"""
serializer_class = settings.SERIALIZERS.user_update_profile
permission_classes = [permissions.IsAuthenticated]
def get_object(self):
return self.request.user
def patch(self, request):
testmodel = self.get_object()
serializer = self.serializer_class(testmodel, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(data=serializer.data, status=status.HTTP_200_OK)
return Response(data=serializer._errors, status=status.HTTP_400_BAD_REQUEST)
但是如果我为角色发送长度为零的字符串,它将返回状态200并且不会更新角色字段
尽管事实上在models.py中角色存在约束,该字段必须位于ROLE_CHOICES
如何使用模型中的验证来更新视图以验证模型中的数据正确?我找不到
型号:
class SeaUser(AbstractUser):
...
SARGENT_PEPPER = 'SGT'
COLENAL_MUSTARD = 'COL'
OTHER = 'OTH'
ROLE_CHOICES = (
(SARGENT_PEPPER, _('sargent')),
(COLENAL_MUSTARD, _('colenal')),
(OTHER, _('Other')),
)
role = models.CharField(_('Role'), max_length=3, choices=ROLE_CHOICES, default=CREW)
role
必须是3个值之一。我用以下方法对此进行测试:
def test_update_user_no_role(self):
payload = {"first_name": "foo",
"last_name": "bar",
"role": "",
"preferred_timezone": "UTC"
}
response = self.request_update_user(payload)
modified_user = self.user_model.objects.get(username=self.user_details['username'])
print('mofified role: ', modified_user.role)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(self.user.role, modified_user.role)
序列化器:
class SeaUserCreateSerializer(UserCreateSerializer):
class Meta:
model = User
fields = ('id',...,'role', 'gdpr',..)
def validate_gdpr(self, value):
if not validate_user_gdpr(value):
raise serializers.ValidationError("GDPR must be accepted.")
return value
视图: