简体   繁体   中英

How to upload images in Django

I want to upload thumbnail into media/thumbnails folder, however

my images uploads to media/thumbnails/thumbnails folder.

How can I fix this?

All my code

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/'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM