1

I'd like to resize image and save it to Database on Django. I found several web sites mentioned about resize of Django, some write in models.py, but the others write in views.py. In which file should I write codes, views.py or models.py?

from PIL import Image
img = Image.open('original.jpg', 'r')
img.thumbnail((100, 100), Image.ANTIALIAS)
img.save('thumbnail.jpg', 'JPEG', quality=75, optimize=True)

models.py

class Photo(models.Model):
    photo = models.ImageField(upload_to="...")
    def save(self, *args, **kwargs):
        do_somehting()
        super(Photo, self).save()
yamachan
  • 1,029
  • 2
  • 12
  • 28
  • 1
    There is no definitive answer to that. When will image resize occur? On page load? On item save? You can always put this code in a separate py file anyway. It's all up to how you want to have your code organized. – Wtower Apr 18 '16 at 10:29
  • @Wtower Thank you for your reply. Sorry, my question was obscure. For Instance, it occurs when a user upload his/her photo. – yamachan Apr 18 '16 at 14:21
  • 1
    Take a look at this one, covers also your question: http://stackoverflow.com/questions/1164930/image-resizing-with-django – Wtower Apr 18 '16 at 14:55
  • @Wtower Sorry for late reply. The link is very nice. One of answers only use PIL and doesn't use libraries. I learned a lot. Thank you. – yamachan Apr 20 '16 at 12:48

2 Answers2

2

I think the best practice is when you use background jobs such as celery or something else, and call it in model saving mode.

It's better to use Pillow package and sorl and its thumbnail to make any size thumbnail and index it automatically via redis

Consider this gist:

import picke
create_thumbnail_images.apply_async([pickle.dumps(self.image_path), USER_IMAGE_THUMB_SIZES], countdown=5)

You can can above sample code in save action of your model to create thumbnails in background, so you never become blocked for creating these thumbnails.

Moe Far
  • 2,742
  • 2
  • 23
  • 41
1

You could use imagekit for that, eg:

from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import Resize

class SomeModel(models.Model):
    ...
    photo = models.ProcessedImageField(upload_to="...", processors=[Resize(650, 402))

In your models seems better, since the picture will always be resized (in your website's actions and in the admin panel).

ddalu5
  • 401
  • 4
  • 17