Django文件上传
需求
- 完成学生信息注册操作
- 将学生信息入库
- 将上传文件存放至项目下media文件夹下
- 显示所有学生信息
创建模型类
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)
]
创建视图
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
Title
编号 |
姓名 |
年龄 |
头像 |
{% for stu in stulist %}
{{ forloop.counter }} |
{{ stu.sname }} |
{{ stu.age }} |
|
{% endfor %}