我是DRF的新手,我有这个序列化器,但我无法创建帖子,因为即使在将图像上传到该字段后,它也会在postman中不断向我显示这一点。在正常的django中,此PostImage模型与Post有外键关系,我使用表单集上传多张图像。
{
"postimage": [
"This field is required."
]
}
有人能帮我解决这个问题并告诉我它是如何工作的吗?
序列化程序。py公司
class PostImageSerializer(serializers.ModelSerializer):
class Meta:
model = PostImage
fields = ['id','post', 'images',]
class PostCreateSerializer(serializers.ModelSerializer):
postimage = PostImageSerializer(many=True)
class Meta:
model = Post
fields = ['id','title', 'image', 'postimage',]
意见。py公司
def create_post_api_view(request):
user = request.user
post = Post(user=user)
serializer = PostCreateSerializer(post, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
更新:
有效载荷。
Authorization: Token XXXX
:
User-Agent: PostmanRuntime/7.26.2
Accept: */*
Postman-Token: 066c9a26-af76-4a44-9e9f-a3326050fa"
Host: 127.0.0.1:8000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------554448102853056787089432
Content-Length: 123293
Request Body
title: "Another Trial api posts"
image: {…}
_events: {}
_eventsCount: 3
_readableState: {…}
autoDestroy: false
awaitDrain: 0
buffer: {…}
head: null
length: 0
tail: null
decoder: null
defaultEncoding: "utf8"
destroyed: true
emitClose: false
emittedReadable: false
encoding: null
endEmitted: true
ended: true
flowing: true
highWaterMark: 65536
length: 0
needReadable: false
objectMode: false
paused: false
pipes: null
pipesCount: 0
readableListening: false
reading: false
readingMore: false
resumeScheduled: false
sync: false
autoClose: true
bytesRead: 5473
closed: true
fd: null
flags: "r"
mode: 438
path: "C:\Users\danny\Desktop\test images\cat.jpg"
readable: false
postimage: [2]
0: {…}
_events: {}
_eventsCount: 3
_readableState: {…}
autoDestroy: false
awaitDrain: 0
buffer: {…}
decoder: null
defaultEncoding: "utf8"
destroyed: true
emitClose: false
emittedReadable: false
encoding: null
endEmitted: true
ended: true
flowing: true
highWaterMark: 65536
length: 0
needReadable: false
objectMode: false
paused: false
pipes: null
pipesCount: 0
readableListening: false
reading: false
readingMore: false
resumeScheduled: false
sync: false
autoClose: true
bytesRead: 7350
closed: true
fd: null
flags: "r"
mode: 438
path: "C:\Users\danny\Desktop\test images\041520_mt_supernova_feat-1028x579.jpg"
readable: false
1: {…}
_events: {}
_eventsCount: 3
_readableState: {…}
autoDestroy: false
awaitDrain: 0
buffer: {…}
decoder: null
defaultEncoding: "utf8"
destroyed: true
emitClose: false
emittedReadable: false
encoding: null
endEmitted: true
ended: true
flowing: true
highWaterMark: 65536
length: 0
needReadable: false
objectMode: false
paused: false
pipes: null
pipesCount: 0
readableListening: false
reading: false
readingMore: false
resumeScheduled: false
sync: false
autoClose: true
bytesRead: 109530
closed: true
fd: null
flags: "r"
mode: 438
path: "C:\Users\danny\Desktop\test images\Tischvase-X-Form-VX-silber-dek-Holst-Porzellan.jpg"
readable: false
Response Headers
Date: Mon, 27 Jul 2020 10:09:18 GMT
Server: WSGIServer/0.2 CPython/3.8.2
Content-Type: application/json
Vary: Accept, Accept-Language, Cookie
Allow: POST, OPTIONS
X-Frame-Options: SAMEORIGIN
Content-Length: 41
Content-Language: en
Response Body
{"postimage":["This field is required."]}
更新的createserializer
class PostCreateSerializer(serializers.ModelSerializer):
images = serializers.ImageField()
class Meta:
model = Post
fields = ['id','title','image', 'images',]
def create(self,validated_data):
user = self.context['request'].user
title = validated_data['title']
image = self.context['request'].FILES.get('image')
images = self.context['request'].FILES.get('images')
m1 = Post(
title=title,
image=image,
user=user
)
m1.save()
m2 = PostImage(
post=m1,
images=images
)
m2.save()
validated_data['images']=m2.images
return validated_data
基于上次编辑的响应
{
"title": "Another Trial api posts",
"image": null,
"images": "http://127.0.0.1:8000/media/posts/postimage/Tischvase-X-Form-VX-silber-dek-Holst-Porzellan.jpg"
}
现在,另一个图像为空。。
谢谢
我认为您应该为您的序列化程序编写自己的创建方法。类似于这样
模型
class MyModel(models.Model):
field1 = models.CharField(max_length=50)
def __str__(self):
return str(self.field1)
class MyModel2(models.Model):
field2 = models.CharField(max_length=50)
image = models.ImageField(upload_to='images')
foreignkeytomymodel = models.ForeignKey(MyModel,on_delete=models.CASCADE)
def __str__(self):
return str(self.field2)
串行器
class MyModelSerializer(serializers.ModelSerializer):
field2 = serializers.CharField(required=True)
image = serializers.ImageField(required=True)
class Meta:
model = MyModel
fields = ['field1','field2', 'image']
def create(self,validated_data):
field1 = validated_data['field1']
field2 = validated_data['field2']
image = self.context['request'].FILES.get('image')
m1 = MyModel(
field1=field1
)
m1.save()
m2 = MyModel2(
field2=field2,
image=image,
foreignkeytomymodel=m1
)
m2.save()
validated_data['field2']=m2.field2
validated_data['image']=m2.image
return validated_data
视图
serializer = MyModelSerializer(data=request.data, context={'request':request})
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
基于序列化程序更新-
class PostCreateSerializer(serializers.ModelSerializer):
images = serializers.ImageField()
class Meta:
model = Post
fields = ['id','title','image', 'images',]
def create(self,validated_data):
user = self.context['request'].user
title = validated_data['title']
image = self.context['request'].FILES.get('image')
images = self.context['request'].FILES.get('images')
m1 = Post(
title=title,
image=image,
user=user
)
m1.save()
m2 = PostImage(
post=m1,
images=images
)
m2.save()
validated_data['image']=m1.image
validated_data['images']=m2.images
return validated_data
model.py serializers.py 如果我尝试: 它会返回错误: 如果我将“finish_date”设置为空,则此帖子有效。并且不会得到错误。 怎么解决?
我想我会在这里问这个问题,因为我不太确定我会错在哪里。我正在尝试使用Django Rest框架类通过AJAX执行POST请求。但是,每当事件触发时,我都会收到以下错误: 这是堆栈跟踪中显示的内容: 上下文 我试图做到这一点,当用户单击“添加到列表”按钮时,它会向用户定义的列表发送一个cafeName(以及最终的其他详细信息)。 我想知道是否有人可以看看我的代码,并给我一些指导,我哪里出了问题? 代
我需要在上传字段中显示保存的文件名。我怎么才能做到?这是我_代码form.php
我是个新手。我正在尝试学习android。我正在使用android教程构建第一个应用程序。我转到<code>新建 然后,我将应用程序名称插入为“我的第一个应用程序”。接下来,使用默认值。在“创建活动”窗口中,选择空白活动并单击“下一步”。 现在问题出现了。在下一个屏幕上,它只显示三个字段: 1) 活动名称 2)布局名称 3) 导航类型
我正在尝试反序列化/读取avro文件,Avro数据文件没有新字段。即使新字段在模式中被声明为null,它也应该是可选的。但是它仍然给我一个强制性的错误。 线程“main”org . Apache . avro . avrotypeexception中出现异常:找到com.kiran.avro.User,应为com.kiran.avro.User,缺少必需字段loc AVRO 架构声明: 使用代码读
问题: 我需要如何/做什么才能让java-ascii-table在给定的上下文中显示testObject的字段值? 背景: 这是我建立的一个小程序,用来测试我正在开发的“显示器类”。在我构建/测试Displayer的应用程序中,我从. csv中读取数据,然后将其分配给产品实例 在当前迭代中,我使用的是java-ascii-table。这个小测试程序重新创建了我的基本需求:创建一个表,显示Array