Search code examples
djangodjango-modelsdjango-staticfilesimagefield

Django - ImageField, upload, store and serve image in development server


I'd like to have an ImageField in the admin form for my model (say, for an individual's profile). And I'd like to display this image in a view later on.

This is the model I have :

class Individual(models.Model):
    ind_name = models.CharField(max_length=100)
    ind_photo = models.ImageField(default="default.jpg")

    def __str__(self):
        return self.ind_name

This is what I have in the settings for my website :

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_URL = '/static/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,"static/media")

These are the urls of my app:

urlpatterns = [
    url(r'^$', views.index, name="index")
]

I know how to use static files (e.g. CSS, Javascript), and to get them to work in both development and production. But I have no clue how to get images to work. I've read Managing static files and Deploying static files, but I still don't get it.

With the code above the image gets saved in the proper folder (i.e. /static/media at the level of my site). But I have no clue :

1) how to display it in a template,

2) whether it would be best to keep these images in my app's static folder,

3) and (if 2) whether I would need to run collectstatic every time someone uploads an image in the admin.

Sorry if I'm unclear, but this way more obscure than I thought it would be.


Solution

  • In order for the image to be uploaded and served during development, I had to move the media folder out of the static folder (i.e. create a media folder at the root of my project's folder).

    And in my main urls.py, I had to add :

    from django.conf import settings
    from django.conf.urls.static import static
    
    if settings.DEBUG: 
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    as suggested by MicroPyramid.

    To display it in a template, for a given Individual "somebody" (from a queryset), I use :

    <img src="{{ somebody.ind_photo.url }}">