1.在主项目的settings.py中配置图片的位置
方法一:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(file),'../media/')
方法二:
底部变为:
STATIC_URL = '/static/'
SESSION_EXPIRE_AT_BROWSER_CLOSE=True
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/dw/'
2.在主项目urls.py中也配置图片
方法一:
import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
方法二(不用导包):
url(r'^dw/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
3.在models.py中创建存储图片的表
class Upload(models.Model):
file_name = models.CharField(max_length=32)
file_type = models.CharField(max_length=32)
file_path = models.FileField(upload_to='filename', blank=True, null=True)
4.在与templates同级目录(即在应用名下)创建media/images中保存需要添加到库中的图片
5.在views.py中添加保存和显示图片的方法
from crudAp.constans import *
from PIL import Image
def upload(request):
name = request.POST.get('file_name', '')
type = request.POST.get('file_type', '')
img = request.FILES['file_path']
obj = Upload(
file_name=name, file_type=type, file_path=img
)
obj.save()
files = Upload.objects.all()#显示图片
return render(request, SHOW_PICTURE_HTML)
6.创建显示图片的页面
<body>
{% for foo in files %}
<img src='/media/{{ foo.file_path }}' width="300"/> //media与setting和主url中的文件名(dw)保持一致
{% endfor %}
</body>