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

4👍

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 }}">

0👍

It is good practice to separate both staticfiles and media files. Yes, you have to do collectstatic all the time when you upload if you store the images in static folder. We can get the image full url from the object like the following.

{{obj.ind_photo.url}}

For more info on files https://docs.djangoproject.com/en/1.10/topics/files/

Leave a comment