Skip to content

Instantly share code, notes, and snippets.

@cb109
Last active January 10, 2023 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cb109/1ff1a7ae7201d907a60d8c2ad8538ff6 to your computer and use it in GitHub Desktop.
Save cb109/1ff1a7ae7201d907a60d8c2ad8538ff6 to your computer and use it in GitHub Desktop.
Integrate Dropzone UI with jquery AJAX POST and django-filer FilerImageField
<head>
<link rel="stylesheet" href="/static/css/dropzone.css">
<script type="text/javascript" src="/static/js/dropzone.js"></script>
</head>
<form
id="my-dropzone-form"
class="dropzone"
action="/cannot-be-empty-but-is-not-used-instead-see-submit.js"
></form>
// We only want to use the DnD UI on the frontend, but not use the Dropzone form's
// submission itself, instead submission is handled by some handler that populates
// a FormData payload manually.
var formData = new FormData();
var dropzoneForm = $('#my-dropzone-form');
var images = dropzoneForm.getQueuedFiles();
for (const image of images) {
formData.append('images', image);
}
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function() {}
});
from filer.fields.image import FilerImageField
class MyModel(models.Model):
image = FilerImageField(on_delete=models.CASCADE)
# The annoying and rather undocumented part is the fact that we need to wrap the
# incoming FILES payload into the File and Image objects before trying to assign
# it to the FilerImageField.
from django.core.files import File
from filer.models import Image
def create_mymodel_from_images(request):
for image in request.FILES.getlist("images"):
file_obj = File(image)
filer_image = Image.objects.create(
owner=request.user, original_filename=image.name, file=file_obj
)
mymodel.objects.create(image=filer_image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment