Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django image src not found

Tags:

python

django

\project_structure
-app
\project
  -settings.py
  -...
\picture
  -panda.jpg

I've uploaded the picture into picture.

class Goods(models.Model):
    pic = models.ImageField(upload_to='picture')

And the data in database is picture/panda.jpg

Now,how can i show it in html?

I wrote this in html:

<p>{{each.pic}}</p>
<img src='{{ each.pic.url }}' />

And the source codes in browser is this:

picture/panda.jpg
<img src='picture/panda.jpg' />

The image was linked to http://localhost:8000/my_sell/picture/panda.jpg.And couldn't show.

How can i solve this,I've tried add media_root in settings.py and useless.

like image 223
M1nt_zwy Avatar asked Dec 01 '16 04:12

M1nt_zwy


1 Answers

I did not check this but almost all code are taken from my working projects :).

settings.py:

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

models:

from django.core.files.storage import FileSystemStorage
from django.conf import settings


image_storage = FileSystemStorage(
    # Physical file location ROOT
    location=u'{0}/my_sell/'.format(settings.MEDIA_ROOT),
    # Url for file
    base_url=u'{0}my_sell/'.format(settings.MEDIA_URL),
)


def image_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/my_sell/picture/<filename>
    return u'picture/{0}'.format(filename)


class Goods(models.Model):
    pic = models.ImageField(upload_to=image_directory_path, storage=image_storage)

views:

from django.shortcuts import render

def view_picture(request):
    c = dict()
    c['goods'] = Goods.objects.all()
    return render(request, 'template.html', c)

templates:

{% for product in goods %} 
    {% if product.pic %}    
        <img src="{{ product.pic.url }}">
    {% endif %}
{% endfor %}

Edited: Don't forget to add MEDIA_URL into root urls.py

if settings.DEBUG
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
like image 51
valex Avatar answered Oct 15 '22 14:10

valex