參考博客:http://www.cognize.me/2016/05/09/djangopichtml
開始以前要先安裝python圖像處理庫:
pip install --use-wheel Pillowpython
命令行:python manage.py startapp img_db數據庫
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'img_db', 'corsheaders', ]
例如:django
class IMG(models.Model): img = models.ImageField(upload_to='img') name = models.CharField(max_length=20)
這裏的upload_to是指定圖片存儲的文件夾名稱,上傳文件以後會自動建立session
python manage.py makemigrations
python manage.py migrateapp
只須要在最後的靜態文件區加上下面兩行代碼:cors
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') #設置靜態文件路徑爲主目錄下的media文件夾 MEDIA_URL = '/media/' #url映射
注意:這是django默認的形式,若是想把模板放在其餘路徑,得本身從新配置。函數
uploadimg.htmlpost
<form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img"> <button type="submit">上傳</button> </form>
showimg.htmlurl
{% for img in imgs %} <img src="{{ img.img.url }}" /> {% endfor %}
這裏img是Django的Model裏的一個實例對象,使用img.img.url能夠獲取他的url,並且在settings.py中已經對其作了靜態映射
@csrf_exempt def uploadImg(request): if request.method == 'POST': new_img = IMG( img=request.FILES.get('img'), name = request.FILES.get('img').name ) new_img.save() return render(request, 'img_tem/uploadimg.html')
首先用get方式訪問uploadImg(),而後會跳轉到uploadimg.html頁面,上傳文件時會使用post再次訪問uploadImg(),這時就會將圖片存儲在數據庫與media/img_tem中。
@csrf_exempt def showImg(request): imgs = IMG.objects.all() content = { 'imgs':imgs, } for i in imgs: print i.img.url return render(request, 'img_tem/showimg.html', content
from django.conf.urls import url from django.contrib import admin import view from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^upload', view.uploadImg), url(r'^show', view.showImg), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 這句話是用來指定和映射靜態文件的路徑
完成以後就能夠發佈了。