1:在models.py文件中建立數據表
from django.db import models class User(models.Model): img = models.ImageField(upload_to='img',null=True)
因為我是后來添加的圖片字段,所以需要在里面加個null=True,至於Upload_to是文件板寸的路徑
2:配置setting.py
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.media',#這個一定要有 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
這個就像配置static差不多,我原本是把MEDIA_URL寫成'/media/'的,不過讀取圖片的時候找不到 改成'Blog/media/'就可以了 Blog是我的項目名
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #設置靜態文件路徑為主目錄下的media文件夾 MEDIA_URL = 'Blog/media/' #url映射
3:執行
python manage.py makemigrations 生成偏移文件
python manage.py migrate 生成數據庫文件
4:templates下的模板文件
(1)upload.html
<form method="POST" enctype="multipart/form-data" > {% csrf_token %} <input type="file" name="img"> <button type="submit">上傳</button>
首先需要一個form,enctype="multipart/form-data" method="post" 是必須要填寫的,表示數據不經過編碼,直接上傳。{%csrf_token%}也是post時,django強制要求的。
(2)showing.html
{% for image in imgs %} {% if image.img %} {# 這種方式也可以打開圖片<img src="{{ MEDIA_URL }}{{ image.img }}" />#} <img src="{{ image.img.url }}" /> {% endif %} {% endfor %}
5:配置urls
url(r'^upload', views.uploadImg), url(r'^show', views.showImg,name='showimg'),
6:views.py
# 上傳圖片 def uploadImg(request): if request.method == 'POST': new_img = Loginon( img=request.FILES.get('img') ) new_img.save() return render(request, 'img_tem/uploadimg.html') # 顯示圖片 def showImg(request): imgs = Loginon.objects.all() content = { 'imgs':imgs, } return render(request, 'img_tem/showimg.html', content)