I am having a lot of trouble trying to code the correct model to upload multiple images to my Django app. I want to be able to upload these images via the django admin. I have tried using ImageField but it only allows one pic at a time and I also want to be able to resize the image.
Here is my models.py:
class Lesson(models.Model):
DRAFT = 'draft'
PUBLISHED = 'published'
CHOICES_STATUS = (
(DRAFT, 'Draft'),
(PUBLISHED, 'Published')
)
ARTICLE = 'article'
QUIZ = 'quiz'
CHOICES_LESSON_TYPE = (
(ARTICLE, 'Article'),
(QUIZ, 'Quiz')
)
course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE)
title = models.CharField(max_length=255)
slug = models.SlugField()
short_description = models.TextField(blank=True, null=True)
long_description = models.TextField(blank=True, null=True)
status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PUBLISHED)
lesson_type = models.CharField(max_length=20, choices=CHOICES_LESSON_TYPE, default=ARTICLE)
Serializer.py:
class LessonListSerializer(serializers.ModelSerializer):
class Meta:
model = Lesson
fields = ('id', 'title', 'slug', 'short_description', 'long_description')
Admin.py:
class LessonAdmin(admin.ModelAdmin):
list_display = ['title', 'course', 'status', 'lesson_type']
list_filter = ['status', 'lesson_type']
search_fields = ['title', 'short_description', 'long_description']
inlines = [LessonCommentInline]
CodePudding user response:
If you want multiple images you need to create another table for images (One2Many relationship).
pip install --upgrade Pillow
# if needed
# import PIL for image resizing
from PIL import Image
class Photo(models.Model):
lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='photos')
photo = models.ImageField(upload_to ='photos/')
# resizing the image, you can change parameters like size and quality.
def save(self, *args, **kwargs):
super(Photo, self).save(*args, **kwargs)
img = Image.open(self.photo.path)
if img.height > 1125 or img.width > 1125:
img.thumbnail((1125,1125))
img.save(self.photo.path,quality=70,optimize=True)
And for the admin you can do:
admin.py
class PhotoAdmin(admin.StackedInline):
model = Photo
class LessonAdmin(admin.ModelAdmin):
inlines = [PhotoAdmin]
class Meta:
model = Lesson
admin.site.register(Photo)
admin.site.register(Lesson, LessonAdmin)