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 = 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.*)/$', 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

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 注册界面



    
    Title


    
{% csrf_token %}

姓名

年龄

照片

  • show.html 显示数据 加载图片



    
    Title


    
        {% for stu in stulist %}
        
        {% endfor %}
    
编号 姓名 年龄 头像
{{ forloop.counter }} {{ stu.sname }} {{ stu.age }}

你可能感兴趣的:(django 图片上传数据库并显示)