Skip to content

Instantly share code, notes, and snippets.

@Marceloromeugoncalves
Created October 20, 2021 00:52
Show Gist options
  • Save Marceloromeugoncalves/270ef6cf7bb987484c488ac6102bd92a to your computer and use it in GitHub Desktop.
Save Marceloromeugoncalves/270ef6cf7bb987484c488ac6102bd92a to your computer and use it in GitHub Desktop.
Redimensionando uma imagem ao salvar um model no Django.
#models.py
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self):
super().save()
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment