django實現圖片上傳數據庫並顯示

Django文件上傳,供大傢參考,具體內容如下

需求

1、完成學生信息註冊操作
2、將學生信息入庫
3、將上傳文件存放至項目下media文件夾下
4、顯示所有學生信息

創建模型類

class Student(models.Model):
    sno = models.AutoField(primary_key=True)
    sname = models.CharField(max_length=30)
    photo = models.ImageField(upload_to='imgs')
    <!--內部類寫法 數據庫中的名字-->
    class Meta:
        db_table = 't_stu'

    def __str__(self):
        return self.sname

settings.py文件中文件上傳相關設置

INSTALLED_APPS = [
    ...
    'stu'
]

DATABASES = {
     'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django22',
        'USER': 'root',
        'PASSWORD': '123321',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

MEDIA_URL = '/media/'
<!--設置MEDIA_ROOT 默認為空  模型類中圖片上傳地址 MEDIA_ROOT+up_load -->
<!--BASE_DIR 為項目錄 -->
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

映射數據庫表

#在終端中敲命令
python manage.py makemigrations test
python manage.py migrate

配置URL

主路由

from django.contrib import admin
from django.urls import path, re_path,include

from djurls.settings import MEDIA_ROOT
from stu import urls
from .import views

#配置路由讀取後臺上傳文件
from django.views.static import serve
urlpatterns = [
     path('test/',include('test.urls')),

re_path(r'^media/(?P<path>.*)/$', serve, {"document_root": MEDIA_ROOT}),
#server 視圖函數 將MEDIA的路徑和正則匹配的模板路徑 顯示圖片

子路由

from django.urls import path

from test import views


urlpatterns = [
    path('test/',views.index.as_view()),
    path('show/',views.show)

]

創建視圖

stu/views.py

import os

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render
from django.views import View

from djurls.settings import BASE_DIR
from test.models import Student
<!--通過as_view處理自動獲取請求方式-->
class index(View):
    def get(self,request):
        return render(request,'load.html')
    def post(self,request):
        name=request.POST.get('sname','')
        photo=request.FILES.get('photo','')
        age=request.POST.get('age','')
        <!--進行校驗 將文件名的後綴字符串分割 判斷-->
        extenedname=photo.name[photo.name.rindex('.')+1:]
        allowedname=['jpg','png']
        if extenedname not in  allowedname:
            return Http404()
        stu=Student.objects.create(sname=name,age=20,photo=photo)
        if stu:
            return HttpResponse('註冊成功')
        else:
            return HttpResponseRedirect('/test/test/')


def show(request):
    stulist=Student.objects.all()
    return render(request,'show.html',{'stulist':stulist})

創建模板

templates/index.html 註冊界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/test/test/"  method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <p>姓名<input type="text" name="sname"></p>
        <p>年齡 <input type="number" name="age"></p>
        <p>照片 <input type="file" name="photo"></p>
        <input type="submit" value="註冊">
    </form>
</body>
</html>

show.html 顯示數據 加載圖片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table border="1px solid black" cellspacing="0px" width="500px" align="center">

        <tr height="100px" align="center">
            <td >編號</td>
            <td >姓名 </td>
            <td >年齡</td>
            <td >頭像</td>
        </tr>
        {% for stu in stulist %}
        <tr height="100px" align="center">
            <td >{{ forloop.counter }} </td>
            <td >{{ stu.sname }}</td>
            <td >{{ stu.age }}</td>
            <td ><img src="/media/{{%20stu.photo%20}}" alt=""></td>
            <!--讀取photo的路徑 在主路由訪問 通過server處理並顯示-->
        </tr>
        {% endfor %}
    </table>
</body>
</html>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: