gpt4 book ai didi

django - DRF : Remove field on model serializer after validation but before creation (on CreateAPIView)

转载 作者:行者123 更新时间:2023-12-02 23:47:26 25 4
gpt4 key购买 nike

我在网站上有一个联系表单,该表单正在发布到 CreateAPIView 以创建模型的新实例(最终通过电子邮件发送给管理员)。在我的序列化器上,我有一个蜜 jar 字段来帮助拒绝垃圾邮件。

型号:

class Message(models.Model):
name = ...
message = ...

和序列化器:

class MessageSerializer(serializers.ModelSerializer):

# Honeypot field
url = serializers.CharField(allow_blank=True, required=False)

class Meta:
model = Message
fields = '__all__'

def validate_url(self, value):
if value and len(value) > 0:
raise serializers.ValidationError('Spam')
return value

并查看:

class MessageView(generics.CreateAPIView):
''' Create a new contact form message. '''
serializer_class = MessageSerializer

我的问题是,就目前情况而言,当我发布到此 View 时,我收到错误:

TypeError: Got a TypeError when calling Message.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Message.objects.create(). You may need to make the field read-only, or override the MessageSerializer.create() method to handle this correctly.

很明显,seriazlier 正在尝试将 url 字段保存到 CreateApiView.perform_create()

中的模型中

我尝试将 read_only 添加到序列化器字段,但这意味着完全跳过 url_validate 方法。

如何在验证发生之前将该字段保留在序列化器上,并在 perform_create() 中调用 serializer.save() 之前将其删除?

最佳答案

您可以覆盖创建方法,例如:

class MessageSerializer(serializers.ModelSerializer):

# Honeypot field
url = serializers.CharField(allow_blank=True, required=False)

class Meta:
model = Message
fields = '__all__'

def validate_url(self, value):
if value and len(value) > 0:
raise serializers.ValidationError('Spam')
return value

def create(self, validated_data):
data = validated_data.pop('url')
return Message.objects.create(**data)

关于django - DRF : Remove field on model serializer after validation but before creation (on CreateAPIView),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34050624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com