Created
June 14, 2016 19:29
-
-
Save rafaelcanovas/47fb0b426d6fc8f39e3a760930240c23 to your computer and use it in GitHub Desktop.
A widget that shows the current image thumbnail instead of clear/modify controls.
This file contains hidden or 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
function styleFileUploader(fileInputId) { | |
var fileInput = $(fileInputId), | |
addFileField = fileInput.siblings('button'); | |
fileInput.hide(); | |
addFileField.on('click touchstart', function (e) { | |
fileInput.trigger('click').trigger('touchstart'); | |
}); | |
fileInput.on('change', function (e) { | |
var input = $(this), | |
reader = new FileReader(); | |
reader.onload = function (e) { | |
addFileField.css('background-image', 'url(' + e.target.result + ')') | |
.addClass('loaded'); | |
}; | |
reader.readAsDataURL(this.files[0]); | |
}); | |
} | |
styleFileUploader('#id_photo', true); |
This file contains hidden or 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 django.utils.safestring import mark_safe | |
from django.forms.widgets import FileInput | |
from django.conf import settings | |
class ThumbnailImageWidget(FileInput): | |
""" | |
A FileField Widget that displays an image instead of a file path | |
if the current file is an image. | |
""" | |
def render(self, name, value, attrs=None): | |
output = [] | |
file_name = str(value) | |
file_thumb = ''' | |
<button type="button" class="upload-photo loaded" style="background-image:url({})"> | |
<span>+ Carregar imagem</span> | |
</button> | |
''' | |
if file_name: | |
file_path = '{}{}'.format(settings.MEDIA_URL, file_name) | |
output.append(file_thumb.format(file_path)) | |
else: | |
output.append(file_thumb.format('')) | |
output.append(super().render(name, value, attrs)) | |
return mark_safe(''.join(output)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment