Django Image Src Not Found
\project_structure -app \project -settings.py -... \picture -panda.jpg I've uploaded the picture into picture. class Goods(models.Model): pic = models.ImageField(upload_
Solution 1:
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),
)
defimage_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/my_sell/picture/<filename>returnu'picture/{0}'.format(filename)
classGoods(models.Model):
pic = models.ImageField(upload_to=image_directory_path, storage=image_storage)
views
:
from django.shortcuts import render
defview_picture(request):
c = dict()
c['goods'] = Goods.objects.all()
return render(request, 'template.html', c)
templates
:
{% for product in goods %}
{% if product.pic %}
<imgsrc="{{ 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)
Post a Comment for "Django Image Src Not Found"