在djang中返回非序列化程序字段otp

2024-04-27 04:55:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将otp与其他序列化程序数据一起返回到我的响应。但由于它不是通过请求提交的,我无法理解如何给予回应。OTP与其他数据完美地存储在用户表中,但我只在返回响应时遇到问题。我的代码如下:

你知道吗型号.py你知道吗

class User(AbstractUser):
    phone_number = models.IntegerField(null=True)
    otp = models.IntegerField(null=True)

你知道吗序列化程序.py你知道吗

class UserSerializer(serializers.ModelSerializer):
  password = serializers.CharField(write_only=True)
  password_confirmation = serializers.CharField(read_only=True)


  class Meta:
    model = User
    fields = ('username', 'password', 'password_confirmation', 'email', 'first_name', 'last_name', 'phone_number')

  def create(self, validated_data):
    password = validated_data.pop('password', None)
    instance = self.Meta.model(**validated_data)
    if password is not None:
        instance.set_password(password)
        instance.save()
    instance.otp = randint(1, 98787)
    instance.save()
    return instance

  def otp(self):
    instance = self.Meta.model()
    return instance.otp

你知道吗视图.py你知道吗

@api_view(['POST'])
def user_signup(request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
    serializer.save()
    content = {'user': serializer.data, 'otp': UserSerializer.otp()}
    return Response(content, status=status.HTTP_201_CREATED)

Tags: instancepyselftruedatamodeldefpassword
1条回答
网友
1楼 · 发布于 2024-04-27 04:55:29

由于serializer.save()返回实例,您可以执行以下操作:

if serializer.is_valid():
    instance = serializer.save()
    content = {'user': serializer.data, 'otp': instance .otp}

所以UserSerializer中的def otp(self)不是必需的。你知道吗

相关问题 更多 >