Skip to content

Instantly share code, notes, and snippets.

@alej0varas
Last active April 13, 2016 11:16
Show Gist options
  • Save alej0varas/5051048 to your computer and use it in GitHub Desktop.
Save alej0varas/5051048 to your computer and use it in GitHub Desktop.
Django Tastypie Base64MultiField for file upload using "application/json" Conten-Type You need a test.png file to test
import base64
from django import forms
from django.core.files.uploadedfile import SimpleUploadedFile
class Base64MultiField(forms.MultiValueField):
def __init__(self, *args, **kwargs):
kwargs['fields'] = (
forms.CharField(),
forms.CharField(max_length=100),
forms.CharField(),
)
super(Base64MultiField, self).__init__(*args, **kwargs)
def compress(self, data_list):
f = SimpleUploadedFile(
data_list[1],
base64.b64decode(data_list[0]),
content_type=data_list[2])
return f
from django import forms
from .forms import Base64MultiField
class PictureForm(forms.Form):
image_full = Base64MultiField(required=True)
import base64
from django.core.files.uploadedfile import SimpleUploadedFile
from tastypie import fields
from tastypie.test import ResourceTestCase
from .forms import Base64MultiField
from .test_forms import PictureForm
class MultiValueFieldTest(ResourceTestCase):
def test_field(self):
data = [base64.b64encode('base64content'), 'image_path.png', 'image/png']
f = Base64MultiField()
data = f.clean(data)
self.assertIsInstance(data, SimpleUploadedFile)
self.assertEqual(data.content_type, 'image/png')
def test_in_form(self):
album = Album.objects.create()
user = User.objects.create()
image_file = open('test.png')
image_content = base64.b64encode(image_file.read())
image_file.close()
data = {'image_full': [image_content, 'image_path.png', 'image/png']}
form = PictureForm(data)
form.is_valid()
obj = form.save()
self.assertIsNotNone(obj.image_full)
self.assertIsNotNone(obj.image_full.path)
self.assertEqual(image_content, base64.b64encode(obj.image_full.file.read()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment