[Answer]-Default Image in Django Rest Framework

1👍

i hit the same issue, i had to explicitly mark my image field in the serializer as blank:

class DetectorSerializer(serializers.ModelSerializer):
    average_image = serializers.ImageField(source='average_image', blank=True)

    class Meta:
        model = Detector
        fields = ('average_image',)

It seems that rest framework is unable to grab it from model or something. After this i am able to POST data to the API using requests like this:

import requests
from requests.auth import HTTPBasicAuth

r = requests.post(
    'http://localhost:8000/detectors/',
    data={'some': 'data'},
    auth=HTTPBasicAuth('user', 'password')
)
print r.text

And this is the response, as you can see it used the default from the model field definition:

{"average_image": "average_image/default.png"}

You can also try to POST with specified file:

r = requests.post(
    'http://localhost:8000/detectors/',
    files={'average_image': open('/path/to/image.jpg')},
    data={'some': 'data'},
    auth=HTTPBasicAuth('user', 'password')
)
print r.text

Hope this helps.

👤jbub

Leave a comment