我正在尝试通过POSTMAN向我的API发送一些图像。
但是,一直以来我都在获取206 status
,如果serializer.is_valid()
不是True
,则会返回该值。此外,serializer.errors
对于每个请求都是空的。
在添加图像字段之前,它工作正常。 MEDIA_ROOT
和MEDIA_URL
字段已经创建。
使用Django的管理页面效果很好。
我正在使用POSTMAN发送请求。 我得到的回应:
{
"data": {}
}
标题:
Accept: application/json
Content-Type: application/json
Models.py
class Order(models.Model):
id = models.UUIDField(
primary_key=True,
db_index=True,
editable=False,
default=uuid4,
)
city = models.CharField(
max_length=50,
verbose_name = (u'City'),
default="NY",
)
description=models.CharField(
max_length=255,
verbose_name=(u'desc'),
default="Офигенная хата",
)
price = models.PositiveIntegerField(
default=0,
verbose_name=(u'Price')
)
requirements = models.CharField(
max_length=50,
verbose_name = (u'Req'),
default="Clean"
)
address = models.CharField(
max_length=50,
verbose_name = (Address'),
default="Wall st"
)
roommates_needed= models.PositiveIntegerField(
verbose_name=(u''),
default=None
)
images = models.FileField(
upload_to = 'pic_folder/%Y/%m/%d/',
default = 'pic_folder/None/no-img.jpg',
verbose_name = (img'),
blank = True,
)
gender_choices=(
(1, u'Lady'),
(2, u'Boy'),
(3, u'anyone')
)
roommate_gender = models.PositiveIntegerField(
choices=gender_choices,
default=3,
verbose_name=(u'gender '),)
status_choices = (
(1, u'Active'),
(2, u'Not active'),
(3, u'Blocked'),
)
status = models.PositiveIntegerField(
default=1,
choices=status_choices,
verbose_name=(u'Status'))
owner = models.OneToOneField(
'User',
on_delete=models.CASCADE,
verbose_name=(u'Owner'),)
def __str__(self):
return self.owner.name
class Meta:
verbose_name = (order')
verbose_name_plural = (u'3. Order list')
serializer.py
def post(self, request, format=None):
serializer = OrderPostSerializer(data=request.data.copy(), partial=True)
queryset = Order.objects.all()
parser_classes = (MultiPartParser,)
## Проверяем совпадает ли токен передаваемый пользователем с тем что в настройках, авторизован он или нет.
if not settings.DEBUG:
token = request.META.get('HTTP_TOKEN', '')
if token != settings.MAINMODULE_TOKEN:
return Response({'detail': 'unauthorized'}, status=status.HTTP_401_UNAUTHORIZED)
if serializer.is_valid() in request.data:
serializer.save()
perform_create()
return Response({'data': serializer.data}, status=status.HTTP_201_CREATED)
else:
return Response({'data': serializer.errors}, status=status.HTTP_206_PARTIAL_CONTENT)
def perform_create(self, serializer):
serializer.save(content_object=self.request.user, image=self.request.FILES.get('images'))
答案 0 :(得分:2)
否,序列化程序无效。这项测试:
if serializer.is_valid() in request.data:
检查请求数据中是否为True(或False),而不是。删除in
:
if serializer.is_valid():
(另外,请注意,未使用您的queryset和parser_classes变量。看起来您已从基于类的视图复制了这些变量,在此函数视图中不需要它们。)