0

我在 django 中创建用户,在使用接收器信号保存配置文件后保存时,我有这样的配置文件模型:

class Profile(models.Model):
    user = models.OneToOneField(base_settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    has_sharkpod = models.BooleanField("The users organization has a sharkpod", default=False)
    role = models.ForeignKey(Role, on_delete=models.DO_NOTHING, default=1)

    def __str__(self):
        return "Profile: " + self.user.username

这是我的榜样:

class Role(models.Model):
role_name = models.CharField(null=True, max_length=100) #unique = true
permissions = JSONField()
user = models.ManyToManyField(
    base_settings.AUTH_USER_MODEL, blank=True)
date = models.DateTimeField(auto_now=True)

现在我也想保存在用户创建的请求正文中传递的角色,但我无法做到这一点。

这是我的个人资料的帖子保存功能:

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created: 
        Profile.objects.create(user=instance)

更新

我的用户视图集:

class CreateUserViewSet(viewsets.ModelViewSet):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAdminUser, IsAuthenticated]
serializer_class = UserSerializer

def post(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.save()
    return Response({
        "user": UserSerializer(user, context=self.get_serializer_context()).data,

    })

还有我的用户序列化器:

class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = ('username', 'email', 'first_name',
              'last_name', 'id', 'is_active', 'password', 'profile')
    read_only_fields = ('profile', 'is_active', )
def create(self, validated_data):
    user = User.objects.create_user(**validated_data)
    password = validated_data.pop('password')
    user.set_password(password)
    return user

我正在从邮递员那里发布这些数据:

 {
  "username": "testUser",
  "email": "bol@example.com",
  "first_name": "test",
  "last_name": "user",
  "password": "test21234",
  "role_id":"45"
}

用户创建工作正常,还创建了配置文件。现在我希望将 role_id: 45 保存在数据库中。这没有发生。

4

0 回答 0