Skip to content

Instantly share code, notes, and snippets.

@d7my11
Created April 24, 2016 18:22
Show Gist options
  • Save d7my11/2eb79ee842ac91955201239c35f7e521 to your computer and use it in GitHub Desktop.
Save d7my11/2eb79ee842ac91955201239c35f7e521 to your computer and use it in GitHub Desktop.
tastypie file uploads
# Base Resource
class MultipartResource(object):
def deserialize(self, request, data, format=None):
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/form-data') and not hasattr(request, '_body'):
request._body = ''
return super(MultipartResource, self).put_detail(request, **kwargs)
def patch_detail(self, request, **kwargs):
if request.META.get('CONTENT_TYPE', '').startswith('multipart/form-data') and not hasattr(request, '_body'):
request._body = ''
return super(MultipartResource, self).patch_detail(request, **kwargs)
# Upload Method
def upload(self, request, **kwargs):
self.method_check(request, allowed=['post'])
try:
data = json.loads(request.body)
except Exception:
data = request.POST.copy()
data.update(request.FILES)
name = data.get('name')
if request.FILES.get('avatar'):
user.avatar = request.FILES.get('avatar')
user.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment