django 實現將本地圖片存入數據庫,并能顯示在web上的示例
1. 將圖片存入數據庫
關于數據庫基本操作的學習,請參見這一篇文章:http://chabaoo.cn/article/167141.htm
這里我默認,您已經會了基本操作,能在數據庫中存圖片了,然后,也會用圖形界面操作數據庫中的數據了
2.這里,我先給出我的代碼,能少走些彎路就少走些
a) 項目的urls.py
from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
+號后面的一定要寫,如果想出來結果的話!否則回報一個 404 的錯誤
- b) 應用里的models.py
from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() def __unicode__(self): # 在Python3中使用 def __str__(self): return self.name class IMG(models.Model): img = models.ImageField(upload_to='img') name = models.CharField(max_length=20) def __str__(self): # 在Python3中使用 def __str__(self): return self.name
之后,你要會把IMG這個模式推送到數據庫。
python ./manage.py makemigrations python ./manage.py migrate
c) 應用的views.py
# Create your views here. def hello(request): IMG.objects.filter(name='bg') img = IMG.objects.all() return render(request, 'Welcome.html',{'img':img})
把img這個參數傳過去,傳到Welcome.html
- d) Welcome.html
<!DOCTYPE HTML> <html> <head> <title> welcome </title> </head> <body > {% for i in img %} <img src="{{MEDIA_URL}}{{i.img}}"> {% endfor %} </body> </html>
e) 設置setting.py
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
注意,東西都是配套使用的,如果e中的路徑要變的話,a總的+號后面的也要跟著變化
3. 在http://127.0.0.1:8000/admin/網址上面,上傳你的圖片
以上這篇django 實現將本地圖片存入數據庫,并能顯示在web上的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
淺談python 中的 type(), dtype(), astype()的區(qū)別
這篇文章主要介紹了淺談python 中的 type(), dtype(), astype()的區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04numpy的Fancy Indexing和array比較詳解
這篇文章主要介紹了numpy的Fancy Indexing和array比較詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06