简体   繁体   English

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

[英]DRF Imagefield upload responds with html template instead of JSON

I'm working with Django Rest Framework 3.5.4 Django 1.9 python 3.5 and Angular 1.4.5. 我正在使用Django Rest Framework 3.5.4,Django 1.9 python 3.5和Angular 1.4.5。 I'm having an issue where I can upload/post to an image endpoint but the response I get is the DRF template instead of the JSON that I was expecting. 我遇到一个问题,可以上传/发布到图像端点,但是得到的响应是DRF模板,而不是我期望的JSON。

models.py 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 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 views.py

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

Payload 有效载荷

------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 内容类型

Content-Type:multipart/form-data;

That's content negotiation and the preferred renderer when submitting forms is HTML because that's consistent with browsers. 这是内容协商,提交表单时首选的渲染器是HTML,因为它与浏览器一致。

If you want a JSON response, you should make sure your request set the headers so it gets JSON. 如果您想要JSON响应,则应确保您的请求设置了标头,使其获取JSON。 In other words, you need to set the Accept headers to application/json 换句话说,您需要将Accept标头设置为application/json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM