1

I have an application where I upload images and the images are uploaded to a specific directory but after uploading which works fine if I attenp to click on the image url I get an error which says The current URL, media/gallery/2017/12/28/230-256.png, didn't match any of these and also the image is not displaying in the browser html below is my model and view despite having my media path defined in the settings

Models.py

class Gallery(models.Model):
    name = models.CharField(max_length=400, db_index=True)
    image = models.ImageField(upload_to='gallery/%Y/%m/%d', blank=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.image.url

Views.py

def index(request):
    gallery = Gallery.objects.all()
    context = {
        'gallery': gallery,
        }
    template = 'gallery.html'
    return render(request, template, context)

html

{% if gallery.image %}
           <div><a href="{{ gallery.image.url }}" title="{{gallery.name}}"><img src="{{ gallery.image.url }}"></a></div>
           {% endif %}
King
  • 1,885
  • 3
  • 27
  • 84

2 Answers2

1

While you are developing, in the project urls.py you must add

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

urlpatterns = [

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This will make your uploaded file accessible by the application.

When on a production server, it is better if the webserver itself (apache, nginx, ..) can reach the location where the files are uploaded, you can find how to configure that in other answers (here for nginx, and here for apache

Onirepap
  • 26
  • 1
  • 5
0

Your HTML needs to be something like this:

{% if gallery.image %}
    <div><a href="{{ MEDIA_URL }}{{ gallery.image.url }}" title="{{gallery.name}}"><img src="{{ MEDIA_URL }}{{ gallery.image.url }}"></a></div>
{% endif %}

MEDIA_URL should be configured in settings.py. This should be set to the base URL from where you're serving the files stored in MEDIA_ROOT.

The URL attribute of the image field stores only the relative URL of the image.

Evan Porter
  • 2,987
  • 3
  • 32
  • 44