我需要更新其他用户的用户。
但是当我执行serializer.save()时,它只是不保存到数据库中。
我的用户模型:
class User(AbstractBaseUser, PermissionsMixin):
class Meta:
db_table='empresa_user'
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(verbose_name='User first name', max_length=30, blank=False)
last_name = models.CharField(verbose_name='User last name', max_length=30, blank=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
dt_criacao = models.DateTimeField(null=True, default=timezone.now)
perfil = models.CharField(verbose_name='Perfil do usuário', max_length=1, blank=False, null=False, default='B')
empresa = models.ForeignKey(Empresa, related_name='empresa', on_delete=models.DO_NOTHING, null=False, blank=False, verbose_name='Empresa')
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ('first_name', 'last_name')
def get_full_name(self):
return self.first_name +' '+ self.last_name
def get_short_name(self):
return self.first_name
def __str__(self):
return self.email
我的序列化器:
UserModel = get_user_model()
class UpdateUserPerfilSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
fields = ('perfil', )
def validate_perfil(self, value):
if value not in ('A', 'G', 'B', ):
raise serializers.ValidationError("Perfil inválido")
return value
我的观点:
@api_view(['PUT'])
@permission_classes((permissions.IsAuthenticated,))
def put_user(request, pk):
empresa = get_empresa(request.user)
try:
user = get_user_model().objects.get(empresa=empresa, pk=pk)
except get_user_model().DoesNotExist:
raise Http404
serializer = UpdateUserPerfilSerializer(user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我这样打电话:
curl -X PUT'http://localhost:8080/empresa/usuario/15/' - H'授权:JWT MY_TOKEN'-d'{“perfil”:“B”}'
这是我的回答:
{ “PERFIL”: “A”}