How to crop image with django and fill the user field


(Felix Kimutai) #1

Hello I am following this tutorial on how to crop images by vitor https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html and it is working perfectly , now lets imagine the Photo model has an additional field lets say user and the model now look like this

class Photo(models.Model):
    
    user = models.ForeignKey(User , on_delete=models.CASCADE, blank=True, null=True) # added this field
    file = models.ImageField()
    description = models.CharField(max_length=255, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'photo'
        verbose_name_plural = 'photos'

, how do do you fill this user field with request.user and also crop image at the same time ? I tried modifying views like so

 @login_required
 def photo_list(request):
    photos = Photo.objects.all()
    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():

            # The next two lines are the modifications
            user = request.user # <--- save the user in a variable called user
            form.save(user) # pass the user to the form save method
            
            return redirect('photo_list')
    else:
        form = PhotoForm()
    return render(request, 'album/photo_list.html', {'form': form, 'photos': photos})

and the forms.py I modified like so

  def save(self, user, commit=True):
        photo = super(PhotoForm, self).save(commit=False)
        
        photo.user = user  # save the user here

        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, h+y))
        resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
        resized_image.save(photo.file.path)
        
        if commit:
            photo.save()
        return photo

The above code saves the user but the cropping did not work, How can you save the user and also crop the image at the same time ? Thank you in advance


(Felix Kimutai) #2

I found the solution

def save(self, user, *args, **kwargs):
        self.instance.user = user 
        photo = super(PhotoForm, self).save(*args, **kwargs)
        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, h+y))
        resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
        resized_image.save(photo.file.path)

        return photo