DRF Imagefield上传使用html模板而不是JSON进行响应

时间:2017-04-13 04:11:31

标签: python django django-rest-framework

我正在使用Django Rest Framework 3.5.4 Django 1.9 python 3.5和Angular 1.4.5。我有一个问题,我可以上传/发布到图像端点,但我得到的响应是DRF模板,而不是我期待的JSON。

models.py

class BeforeImage(models.Model):
    job = models.ForeignKey(Job, related_name='before_images')
    before_image = models.ImageField(upload_to='images/', default='images/no-image.jpg')

    def __str__(self):
        return self.pk

    class Meta:
        db_table = 'before_images'

serializers.py

class BeforeImageSerializer(ModelSerializer):
    before_image = ImageField(
        max_length=None, allow_empty_file=False, use_url=True)

    class Meta:
        model = BeforeImage
        fields = ('id', 'job', 'before_image')

views.py

class BeforeImageViewSet(ModelViewSet):
    queryset = BeforeImage.objects.all()
    serializer_class = BeforeImageSerializer

有效载荷

------WebKitFormBoundarybB5wAXF1Q6ZaG9pB Content-Disposition: form-data; name="job" 10 ------WebKitFormBoundarybB5wAXF1Q6ZaG9pB Content-Disposition: form-data; name="before_image"; filename="Screen Shot 2017-04-10 at 11.44.24 PM.png" Content-Type: image/png ------WebKitFormBoundarybB5wAXF1Q6ZaG9pB--

内容型

Content-Type:multipart/form-data;

1 个答案:

答案 0 :(得分:2)

提交表单时,内容协商和首选渲染器是HTML,因为它与浏览器一致。

如果您需要JSON响应,则应确保您的请求设置标头以使其获得JSON。换句话说,您需要将Accept标头设置为application/json