Home > Software design >  Uploading images in django
Uploading images in django

Time:01-20

I have being using django for sometime but recently noticed this. Before now I thought images in django, by default, gets uploaded in the path specified in STATIC_URL but I just saw that the bahaviour is diffrent in my app. I have this set up in settings.py:

class BlogPost(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
    category = models.CharField(max_length=50, choices=Categories.choices, default=Categories.medications)
    title = models.CharField(max_length=50)
    slug = models.SlugField()
    image = ResizedImageField(upload_to='images/blog/', null=True, blank=True)
    introduction = models.CharField(max_length=255)
    body = models.TextField()

settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static',),
    os.path.join(BASE_DIR, 'frontend/build/static'),
    ]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

The static, staticfiles, and media are within the root directory. In my django app, if media directory isn't present the images get uploaded in static directory. However, when both static and media directorie are present preference is given to the media directory (the images get uploaded in media directory). Did I make a mistake somewhere?

CodePudding user response:

STATIC_ROOT was used to store all kinds of files like JavaScript, CSS and media files. Bot now the MEDIA_ROOT is used explicit for images and other media. That's where all you medias should go, you can also create additional directories in MEDIA_ROOT ex. for each model you have. More about MEDIA_ROOT here

  •  Tags:  
  • Related