I want to upload thumbnail into media/thumbnails folder, however
my images uploads to media/thumbnails/thumbnails folder.
How can I fix this?
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = RichTextField(null=True,blank=True)
date_posted = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User,on_delete=models.CASCADE)
topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True)
thumbnail = models.ImageField(default='default.jpg',upload_to='thumbnails/')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={'pk':self.pk})
def save(self, *args, **kwargs):
super(Post, self).save(*args, **kwargs)
new_image = self.crop_max_square(Image.open(self.thumbnail.path)).resize((300, 300), Image.LANCZOS)
new_image_io = BytesIO()
new_image.save(new_image_io, format='JPEG')
temp_name = self.thumbnail.name
self.thumbnail.delete(save=False)
self.thumbnail.save(
temp_name,
content=ContentFile(new_image_io.getvalue()),
save=False
)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
CodePudding user response:
Try replacing this:
temp_name = self.thumbnail.name
with this:
temp_name = os.path.basename(self.thumbnail.name)
You will also need import os.
The Django docs indicate that self.thumbnail.name will return "the name of the file including the relative path...". When you call self.thumbnail.save() it is probably adding 'thumbnails/' to the path as declared in your ImageField.upload_to attribute.
