Last active
January 10, 2023 13:12
-
-
Save cb109/1ff1a7ae7201d907a60d8c2ad8538ff6 to your computer and use it in GitHub Desktop.
Integrate Dropzone UI with jquery AJAX POST and django-filer FilerImageField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() {} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from filer.fields.image import FilerImageField | |
class MyModel(models.Model): | |
image = FilerImageField(on_delete=models.CASCADE) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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