「Python-Django」django 實現將本地圖片存入數據庫,並能顯示在web上


1. 將圖片存入數據庫

關於數據庫基本操作的學習,請參見這一篇博客:https://www.cnblogs.com/leejy/p/6745186.html

這里我默認,您已經會了基本操作,能在數據庫中存圖片了,然后,也會用圖形界面操作數據庫中的數據了

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/網址上面,上傳你的圖片

土拍你

--------------------- 本文來自 竦貊 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/Inuyasha_1314/article/details/80531900?utm_source=copy 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM