django 實(shí)現(xiàn)將本地圖片存入數(shù)據(jù)庫,并能顯示在web上的示例
1. 將圖片存入數(shù)據(jù)庫
關(guān)于數(shù)據(jù)庫基本操作的學(xué)習(xí),請參見這一篇文章:http://www.dhdzp.com/article/167141.htm
這里我默認(rèn),您已經(jīng)會了基本操作,能在數(shù)據(jù)庫中存圖片了,然后,也會用圖形界面操作數(shù)據(jù)庫中的數(shù)據(jù)了
2.這里,我先給出我的代碼,能少走些彎路就少走些
a) 項(xiàng)目的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)
+號后面的一定要寫,如果想出來結(jié)果的話!否則回報(bào)一個 404 的錯誤
- b) 應(yīng)用里的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這個模式推送到數(shù)據(jù)庫。
python ./manage.py makemigrations python ./manage.py migrate
c) 應(yīng)用的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這個參數(shù)傳過去,傳到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) 設(shè)置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/網(wǎng)址上面,上傳你的圖片

以上這篇django 實(shí)現(xiàn)將本地圖片存入數(shù)據(jù)庫,并能顯示在web上的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Django用戶認(rèn)證系統(tǒng) User對象解析
這篇文章主要介紹了Django用戶認(rèn)證系統(tǒng) User對象解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
python 3.74 運(yùn)行import numpy as np 報(bào)錯lib\site-packages\numpy\_
這篇文章主要介紹了python 3.74 運(yùn)行import numpy as np 報(bào)錯lib\site-packages\numpy\__init__.py,原來需要更新一下numpy即可2019-10-10
Python使用pyinstaller實(shí)現(xiàn)學(xué)生管理系統(tǒng)流程
pyinstaller是一個非常簡單的打包python的py文件的庫,下面這篇文章主要給大家介紹了關(guān)于Python?Pyinstaller庫安裝步驟以及使用方法的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02

