Django creates another media folder inside media folder

Viewed 848

I'm a beginner with Django and that's exactly what it does. I do just as it was in the documentation but anyway maybe something went wrong?

From admin-page I adding\setting-up a product and choosing the 'image', then when I'm saving it creating a thumbnail and trying to save in '/media/uploads/' but instead it's creating another 'media' folder and the image stored in '/media/media/uploads/img.png' when path on site is '/media/uploads/img.png'. Here is the code:

/shop/settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # or even 'media/'

/shop/urls.py:
urlpatterns = [
    ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

after that's added, then in my Product model I do:

/apps/store/models.py:
class Product(models.Model):
    ...
    image = models.ImageField(upload_to='media/uploads/', blank=True, null=True)
    thumbnail = models.ImageField(upload_to='media/uploads/', blank=True, null=True)
    ...

    def save(self, *args, **kwargs):
        self.thumbnail = self.make_thumbnail(self.image)
        super().save(*args, **kwargs)

    @staticmethod
    def make_thumbnail(image, size=(512, 512)):
        if not image:
            return

        img = Image.open(image)
        if img.mode in ('RGBA',):  # converting image to RGB if it's RGBA
            img.load()
            rgb_convert = Image.new('RGB', img.size, 0)
            rgb_convert.paste(img, mask=img.split()[3])
            img = rgb_convert

        img.thumbnail(size)

        thumb_io = BytesIO()
        img.save(thumb_io, 'PNG', quality=80)
        thumb = File(thumb_io, name=image.name)
        return thumb

I tried to change 'upload_to' to 'uploads/' and then it stores files in the right direction but path to it on-site also changes to '/uploads/img.png' when it's must be '/media/uploads/img.png'

What's can be wrong? Thanks!

2 Answers

The upload_to=… parameter [Django-doc] is relative to the MEDIA_ROOT. So if you want to store it in a directory uploads in the media directory, you upload this with:

class Product(models.Model):
    # …
    thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True)

In order to render the URL however, you use the .url attribute [Django-doc], so:

{% if p.thumbnail %}
    <img src="{{ p.thumbnail.url }}">
{% endif %}

The {% if p.thumbnail %} is here necessary to check for NULL/None values.

it's cause you wrote "upload_to='media/uploads'".. from your settings django will create media folder and since you wrote "media/uploads" ,uploads is inside the media folder which is inside main media which was declared in settings. So just write

class Product(models.Model):
…
thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True)
Related