0
當發佈這樣的:Django的REST框架錯誤:{ 「用戶」: 「這是必須填寫」]
curl -X POST -H "Authorization: Token sometoken" -d "url=someurl" 127.0.0.1:8000/create/
我得到的錯誤:
{"user":["This field is required."] with the ItemSerializer,
我看到其他職位在談論如何使用perform_create,我試圖用來保存用戶對象,但它不起作用的原因。當用戶這樣定義Perform_create工作:
user = serializers.CharField(
default=serializers.CurrentUserDefault()
)
但我想使用的用戶對象,不僅CharField存儲的用戶名
串行器:
class UserDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = UserModel
fields = ('pk', 'username', 'email', 'first_name', 'last_name')
read_only_fields = ('email',)
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ['cat']
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
fields = [
'comment',
]
class ItemSerializer(serializers.HyperlinkedModelSerializer):
user = UserDetailsSerializer()
category = CategorySerializer(many=True)
thecomments = CommentSerializer(many=True)
timestamp = serializers.SerializerMethodField('get_mytimestamp')
def get_mytimestamp(self, obj):
return time.mktime(datetime.datetime.now().timetuple())
class Meta:
model = Item
fields = [
"url",
"user",
"timestamp",
"categories",
"thecomments",
]
型號:
查看:
class ItemCreateAPIView(generics.CreateAPIView):
serializer_class = ItemSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
解決方案:
串行創建項目:
views.py
class ItemCreateAPIView(generics.CreateAPIView):
serializer_class = CreateSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
後:
curl -X POST -H "Authorization: Token sometoken" -d "url='someurl'" 127.0.0.1:8000/createitem/
我仍然得到相同的錯誤,但它必須處於正確的方向,具有類似{'user':{required:False}}的意義。我也試過 user = UserDetailsSerializer(required = False,read_only = True) 但它給出了:默認情況下,'.create()'方法不支持可寫的嵌套字段。 爲串行化程序'app.serializers.ItemSerializer'編寫明確的'.create()'方法,或者在嵌套序列化程序字段中設置'read_only = True'。 – DevB2F
當使用get請求時,不會出現'此字段是必需的'錯誤,這與發佈時創建用戶對象有關。 – DevB2F
刪除'ItemSerializer'中的'user = UserDetailsSerializer()'時發佈所有將罰款,不同的序列化器發佈和獲取 – Ykh