Source https://www.youtube.com/watch?v=5t6kgAEMIB8
I found this recently it may be helpful:
In your forms.py:
from PIL import Image
from django import forms
from django.core.files import FILE
from .models import YourModel
class YourModelForm(forms.ModelForm):
x = forms.FloatField(widget=forms.HiddenInput())
y = forms.FloatField(widget=forms.HiddenInput())
width = forms.FloatField(widget=forms.HiddenInput())
height = forms.FloatField(widget=forms.HiddenInput())
class Meta:
model = YourModel
fields = '__all__'
exclude = ['user', 'date_joined','Credits_earned','skills']
def save(self):
photo = super(YourModelForm,self).save()
x = self.cleaned_data.get('x')
y = self.cleaned_data.get('y')
w = self.cleaned_data.get('width')
h = self.cleaned_data.get('height')
image = Image.open(photo.file)
cropped_image = image.crop((x,y,w+x,w+y))
resized_image = cropped_image.resize((1200,600), Image.ANTIALIAS)
resized_image.save(photo.file.path)
return photo
And here's the JS to handle it in your template:
<script>
$(function () {
// SCRIPT TO OPEN THE MODAL WITH THE PREVIEW
$("id_file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#image").attr("src", e.target.result);
$("#modalCrop").modal("show");
}
reader.readAsDatarURL(this.files[0]);
}
});
// SCRIPTS TO HANDLE THE CROPPER BOX
var $image = $("image");
var cropBoxData;
var canvasData;
$("#modalCrop").on("shown.bs.modal", function () {
$image.cropper({
viewMode: 3,
movable: false,
zoomable: false,
scalable: false,
ready: function () {
$image.cropper("setCanvasData", canvasData);
$image.cropper("setCropBoxData", cropBoxData);
}
});
}).on("hidden.bs.modal", function () {
cropBoxData = $image.cropper("getCropBoxData");
canvasData = $image.cropper("getCanvasData");
$image.cropper("destroy");
});
$(".js-zoom-in").click(function () {
$image.cropper("zoom", 0.1);
});
$(".js-zoom-out").click(function () {
$image.cropper("zoom", -0.1)
});
// SCRIPT TO COLLECT THE DATA AND POST TO THE SERVER
$(".js-crop-and-upload").click(function () {
$("#id_x").val(cropData["x"]);
$("#id_y").val(cropData["y"]);
$("#id_height").val(cropData["height"]);
$("#id_width").val(cropData["width"]);
$("#formUpload").submit;
});
});
</script>
you can chanage the id manually in the script in order to match your template, or you could use the one in the video () although you will have to pause it and code it. Also if you use Function-Based-Views instead of Class-Based-Views you will have to add the files to the form validation for example:
def YourView(request)
if request.method == 'POST':
form = YourModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
return redirect('Your_redirect_URL')
else:
form = YourModelForm()
return render(request, 'YourTemplate.html', {'form': form})