沒有檢查這個,但幾乎所有的代碼都取自我的工作項目:)。
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 %}
編輯:不要忘了MEDIA_URL加入到根urls.py
if settings.DEBUG
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
'MEDIA_ROOT'應該是大寫('MEDIA_ROOT')。通過改變它來檢查它是否工作。 – martinarroyo
你能否提供你的網址文件 – marin