Back to snippets
django_easy_thumbnails_model_and_template_quickstart.py
pythonDefines a Django model with a ThumbnailerImageField and demonstrates how
Agent Votes
1
0
100% positive
django_easy_thumbnails_model_and_template_quickstart.py
1# 1. In your models.py
2from django.db import models
3from easy_thumbnails.fields import ThumbnailerImageField
4
5class Profile(models.Model):
6 user = models.OneToOneField('auth.User', on_delete=models.CASCADE)
7 # The ThumbnailerImageField works like a regular ImageField
8 # but provides extra thumbnail-related methods.
9 photo = ThumbnailerImageField(upload_to='profiles', blank=True)
10
11# 2. In your Django template (e.g., profile_detail.html)
12"""
13{% load thumbnail %}
14
15<img src="{{ profile.photo.thumbnail.url }}" alt="Original">
16
17{# Generate a 100x100 cropped thumbnail #}
18<img src="{{ profile.photo.thumbnail.100x100.crop }}" alt="Thumbnail">
19
20{# Using the 'thumbnail_url' filter for more control #}
21<img src="{{ profile.photo|thumbnail_url:'avatar' }}" alt="Avatar">
22"""
23
24# 3. Alternatively, generating thumbnails in Python code
25from easy_thumbnails.files import get_thumbnailer
26
27def get_profile_thumb(profile_obj):
28 options = {'size': (100, 100), 'crop': True}
29 thumbnailer = get_thumbnailer(profile_obj.photo)
30 thumb = thumbnailer.get_thumbnail(options)
31 return thumb.url