0

I am trying to load the uploaded image in the template. The image is getting correctly uploaded and the url is also correct but I am still getting the 404 error. The error is:- GET http://127.0.0.1:8000/media/complaints_image/motivational-inspirational-quotes-30.jpg 404 (Not Found)

The image is present in the folder :- inside the media folder image is present

template

{% if complaint.media %}
 <img src="{{ complaint.media.url }}" height="100px" width="100px" >
{% endif %}

settings.py

MEDIA_DIR  = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

models.py

class Complaints(models.Model):
  media = models.ImageField(upload_to='complaints_image',blank=True)

forms.py

class ComplaintForm(forms.ModelForm):

class Meta():
    model = Complaint
    fields = ('department','heading','text','media',)

1 Answers1

0

You are getting this error because media files are not served automatically (by default).


If your MEDIA_URL is defined as '/media/', then you can serve your media files by adding the following snippet to your entry-level urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Read Serving files uploaded by a user during development for more details.


Note: This way of serving media (and static) files is not suitable for production use!

Read this article for more details on what to do for the production server.

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24