问题
I am trying to upload files via a Multipart/Form-Data form and Tastypie API and am running into some issues:
My Model:
class Client(models.Model):
account = models.ForeignKey(Account)
client_image = models.FileField(upload_to=client_image_path, default="/assets/img/default-user-image.png", blank=True, null=True)
client_image_thumb = models.FileField(upload_to=client_image_thumb_path, default="/assets/img/default-user-image.png", blank=True, null=True)
I am using a custom deserialize method as outlined in Tastypie Issue#42:
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
def put_detail(self, request, **kwargs):
if request.META.get('CONTENT_TYPE').startswith('multipart') and \
not hasattr(request, '_body'):
request._body = ''
return super(MultipartResource, self).put_detail(request, **kwargs)
And here is my corresponding ModelResource:
class ClientResource(MultipartResource, ModelResource):
account = fields.ForeignKey(AccountResource, 'account')
class Meta():
queryset = Client.objects.all()
always_return_data = True
resource_name = 'account/clients/client-info'
authorization = AccountLevelAuthorization()
list_allowed_methods = ['get','post','put','delete','patch']
detail_allowed_methods = ['get', 'post', 'put', 'delete','patch']
authentication = ApiKeyAuthentication()
filtering = {
'username': ALL,
}
If I do a POST with content-type application/JSON and dont include the client_image field, it will successfully create a new Client Object. This indicates that the models/resources are working as they should.
However, when I try to use a Multipart/Form-Data content type I can see that it gets through my deserializer appropriately with this payload:
------WebKitFormBoundaryp0Q7Q9djlsvVGwbb
Content-Disposition: form-data; name="{%0D%0A%22account%22"
"/api/v1/account/account-info/21/",
------WebKitFormBoundaryp0Q7Q9djlsvVGwbb
Content-Disposition: form-data; name="client_image"; filename="donavan.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryp0Q7Q9djlsvVGwbb--
I am also seeing this QueryDict while debugging, which shows the InMemoryUploadedFile correctly:
<QueryDict: {u'client_image': [<InMemoryUploadedFile: donavan.jpg (image/jpeg)>], u'{%0D%0A%22account%22': [u'"/api/v1/account/account-info/21/"']}>
but I keep getting this error:
{ error_message: "" traceback: "Traceback (most recent call last): File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py", line 202, in wrapper response = callback(request, *args, **kwargs) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py", line 440, in dispatch_list return self.dispatch('list', request, **kwargs) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py", line 472, in dispatch response = method(request, **kwargs) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py", line 1328, in post_list updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs)) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py", line 2104, in obj_create bundle = self.full_hydrate(bundle) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py", line 890, in full_hydrate value = field_object.hydrate(bundle) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/fields.py", line 732, in hydrate value = super(ToOneField, self).hydrate(bundle) File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/fields.py", line 165, in hydrate elif self.attribute and getattr(bundle.obj, self.attribute, None): File "/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 343, in get raise self.field.rel.to.DoesNotExist DoesNotExist " }
Any ideas where this could be broken? Thanks in advance!
回答1:
This happened to me when I post a data without providing necessary fields. Those fields that cannot be null must be provided while posting.
来源:https://stackoverflow.com/questions/16088289/django-tastypie-deserializing-multipart-form-data-to-upload-file