当提示PUT(更新)出错时
无法调用.is_valid(),因为在实例化序列化程序实例时没有传递data = keyword参数。 我的观点:
def get_serializer(self, *args, **kwargs):
queryset = Producer.objects.get(pk=self.kwargs['pk'])
if self.request.user.is_authenticated:
return ProducerSerializer(queryset,
fields=('short_info',))
if self.request.method == 'PUT' or self.request.method == 'PATCH':
return ProducerUpdateSerializer
else:
return ProducerSerializer(queryset,
fields=('website', 'phone', 'email', 'contacts', 'short_info'))
def get_queryset(self):
return Producer.objects.filter(pk=self.kwargs['pk'])
我的序列化程序
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
if fields is not None:
for i in fields:
print self.fields.pop(i)
class ProducerSerializer(DynamicFieldsModelSerializer):
tags = TagListSerializerField()
categories = serializers.StringRelatedField(many=True)
contacts = ProducerContactSerializer(many=True)
country = CountryField(country_dict=True)
business_type = ChoicesSerializerField()
class Meta:
model = Producer
fields = ('id', 'business_type', 'logo', 'name', 'slug', 'country', 'city',
'street_address', 'zip', 'short_info', 'info', 'website',
'categories', 'tags', 'contacts', 'email', 'phone')
class ProducerUpdateSerializer(serializers.ModelSerializer):
tags = TagListSerializerField()
categories = serializers.StringRelatedField(many=True)
class Meta:
model = Producer
fields = ('id', 'business_type', 'logo', 'name', 'slug', 'country', 'city',
'street_address', 'zip', 'short_info', 'info', 'website', 'categories', 'tags')
当提示PUT(更新)出错时
无法调用.is_valid(),因为在实例化序列化程序实例时没有传递data = keyword参数。
答案 0 :(得分:0)
首先,我怀疑你的get_serializer
对PUT是否正确。它应该在您返回类时返回一个实例。
至于您的问题,错误消息非常清楚。在实例化它时,您没有将data=request.data
传递给序列化程序。文档包含an example如何执行此操作。