Akanksha
Akanksha

Reputation: 51

Images broken while trying to display it from database in django

Settings.py

STATIC_URL = '/static/'
MEDIA_ROOT='/home/akanksha/bookepdia/media/'
MEDIA_URL = '/media/' 
TEMPLATE_DIRS = ('/home/akanksha/bookepdia/templates',)

Model.py

class Image(models.Model):
title = models.CharField(max_length=255)
photo = models.ImageField(upload_to='/home/akanksha/bookepdia/media/images/')

Url.py

urlpatterns = patterns('',

url(r'^$', 'bookepdia.views.home', name='home'),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Views.py

def home(request):
    photos = Image.objects.all()
    return render_to_response('display.html', {'photos' : photos})

display.html

<html>
<h3>Images of books</h3>
<img src="/media/images/image_name" />
{% for p in photos %}
    <img src="{{p.photo.url}}" />
{% endfor %}
</html>

Now,my problem is when I have added /media/images/image_name the image is displayed but when I use {{p.photo.url}} the image is displayed as broken icon. I found out it is taking the path as /home/akanksha/bookepdia/media/images/image_name. Now,I want to edit this for every url so that it works as /media/images/image_name.

Upvotes: 1

Views: 505

Answers (2)

GwynBleidD
GwynBleidD

Reputation: 20539

You shouldn't give absolute path into upload_to in ImageField, it should be path relative to your MEDIA_ROOT.

Upvotes: 3

Ilya Tikhonov
Ilya Tikhonov

Reputation: 1429

upload_to attribute of ImageField is not absolute path, it is relative to MEDIA_ROOT setting.

In your case it should be like this:

photo = models.ImageField(upload_to='images')

See documentation: https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.FileField.upload_to

FileField.upload_to

A local filesystem path that will be appended to your MEDIA_ROOT setting to determine the value of the url attribute.

Upvotes: 1

Related Questions