爲了利用Django的ImageField和FileField格式實現多圖,多文件上傳,在網上找了好久,基本上不是代碼不全,就是報錯一堆,由於這種格式能夠和django的admin相結合,很是不甘心,終於在今天結合多個demo演練成功了。html
時間有限先貼代碼,有時間再詳細寫註釋python
app結構,其中imgs_db是本次的多圖上傳,files_db是本次多文件上傳mysql
基本工做:jquery
新建app,修改setting.py中的installed_app和靜態路徑,增長媒體路徑sql
STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') #設置靜態文件路徑爲主目錄下的media文件夾 MEDIA_URL = '/media/'
數據庫若是是mysql的請新建好,設置頁面修改(這裏略)數據庫
from django.db import models class Imgs(models.Model): id = models.AutoField(max_length=10, primary_key=True, verbose_name='id') img = models.ImageField(upload_to='./imgs/',verbose_name='圖片地址') single = models.CharField(max_length=20,null=True, blank=True,verbose_name='圖片名稱') def __unicode__(self): # __str__ on Python 3 return (self.id,self.img) def __str__(self): return str(self.single) class Imgs_name(models.Model): id = models.AutoField(max_length=10, primary_key=True, verbose_name='id') name = models.CharField(max_length=10,verbose_name='圖片庫名稱') imgs = models.ManyToManyField(Imgs, related_name='imgs',verbose_name='圖片表') def __unicode__(self): # __str__ on Python 3 return (self.id,self.name,self.imgs) def __str__(self): return self.name
from django.http import HttpResponseRedirect from django.shortcuts import render,HttpResponse from imgs_db.models import Imgs_name,Imgs import random def up_imgs(request): return render(request, 'imgs_tem/up_imgs.html') def upload_imgs(request): ''' model拆分紅2個表,其中一個爲文件存儲,一個爲圖集 圖集對文件存儲中須要有一個字段設置爲多對多的儲存關係 post後得到文件 先對圖集實例化,增長其餘字段應填寫的值,對這個實例存儲 再對多文件列表循環,對圖片自己實例化,增長其餘字段應填寫的值,再對這個實例存儲 最後添加圖片對應圖集的關係表保存 :param request: :return: ''' test = Imgs_name() test.name = 'test' + str(random.randint(100, 900)) test.save() for f in request.FILES.getlist('imgs'): print(f) empt = Imgs() # 增長其餘字段應分別對應填寫 empt.single=f empt.img=f empt.save() test.imgs.add(empt) # File(file=f, files=test,id=1).save() return HttpResponse('上傳成功')
from django.contrib import admin # Register your models here. from imgs_db.models import Imgs,Imgs_name class img_up(admin.ModelAdmin): list_display = ('id','img','single') filter_horizontal = ('imgs',) admin.site.register(Imgs, img_up) class test_img_up(admin.ModelAdmin): list_display = ('id','name') admin.site.register(Imgs_name, test_img_up)
from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from django.conf.urls import url from imgs_db import views as imgs_db urlpatterns = [ url(r'^admin/', admin.site.urls), # 多圖,多文件上傳 url(r'^up_imgs', imgs_db.up_imgs), url(r'^upload_imgs', imgs_db.upload_imgs), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>多圖片上傳</title> <script src="/static/js/jquery-1.8.3.min.js"></script> <style> label{width: 80%;padding: 10px 20px;display: block} label input{border: 1px solid #eee;padding: 10px 20px;margin-left: 20px} </style> </head> <body> <form action="upload_imgs" method="POST" enctype="multipart/form-data"> <label>項目打包圖片<input type="file" name="imgs" multiple></label> <button type="submit">提交</button> </form> </body> </html>
注意form表單要填寫enctype="multipart/form-data"django
文件input類型爲file,支持多文件增長multipleapp
python manage.py migrate python manage.py makemigrations python manage.py migrate python manege.py createsuperuser#建立超級管理員,以後自行設置用戶名密碼
試驗次數多了,發現migrate在makemigrations先後各作一次,能讓數據庫在屢次初始化後叫好用dom
同時上傳2張圖(有的時候會出現data too lang),須要把single字段長度變大post
發現文件已經上傳到路徑
訪問:http://127.0.0.1:8222/admin/
發現文件上傳位置,+能夠繼續添加,這裏的1.png,2.png顯示路徑名稱,是使用內置方法__str__()獲得
有圖單獨增長的圖片名稱是靠增長single字段,而且使用內置方法__str__()獲得(爲了方便上傳後對圖片末尾加隨機字符串串或者重命名而增長)
相應的,在view.py視圖要增長對single的保存
固然點開後就能看到圖片
from django.db import models class Files(models.Model): id = models.AutoField(max_length=10, primary_key=True, verbose_name='id') file = models.FileField(upload_to='./files/') def __unicode__(self): # __str__ on Python 3 return (self.id,self.file) class Files_name(models.Model): id = models.AutoField(max_length=10, primary_key=True, verbose_name='id') name = models.CharField(max_length=10) files = models.ManyToManyField(Files, related_name='files') def __unicode__(self): # __str__ on Python 3 return (self.id,self.name,self.files)
from django.http import HttpResponseRedirect from django.shortcuts import render,HttpResponse from files_db.models import Files_name,Files import random def up_files(request): return render(request, 'files_tem/up_files.html') def upload_files(request): test = Files_name() test.name = 'test' + str(random.randint(100, 900)) test.save() for f in request.FILES.getlist('files'): empt = Files() empt.file = f empt.save() test.files.add(empt) # File(file=f, files=test,id=1).save() return HttpResponse('上傳成功')
from django.contrib import admin # Register your models here. from files_db.models import Files,Files_name class file_up(admin.ModelAdmin): list_display = ('id','file',) admin.site.register(Files, file_up) class test_up(admin.ModelAdmin): list_display = ('id','name') admin.site.register(Files_name, test_up)
from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from django.conf.urls import url from files_db import views as files_db urlpatterns = [ url(r'^admin/', admin.site.urls), # 多圖,多文件上傳 url(r'^up_files', files_db.up_files), url(r'^upload_files', files_db.upload_files), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>多文件上傳</title> <script src="/static/js/jquery-1.8.3.min.js"></script> <style> label{width: 80%;padding: 10px 20px;display: block} label input{border: 1px solid #eee;padding: 10px 20px;margin-left: 20px} </style> </head> <body> <form action="upload_files" method="POST" enctype="multipart/form-data"> <label>項目打包文件<input type="file" name="files" multiple></label> <button type="submit">提交</button> </form> </body> </html>
python manage.py migrate python manage.py makemigrations python manage.py migrate python manege.py createsuperuser#建立超級管理員,以後自行設置用戶名密碼
試驗次數多了,發現migrate在makemigrations先後各作一次,能讓數據庫在屢次初始化後較好用
多文件上傳未對名字進行修改,也沒有多增長字段,爲方便對比多圖上傳添加部分的顯示效果
————————————————————————————————————————————
因爲在創建model.py的時候對數據字段類型作了限制,此處應是圖片的上傳成非圖片的文件,就會報錯。
其餘字段類型也是同樣的。這就是django建立admin的好處,不用寫增刪改查,卻都有,也能判斷