【django学习-27】media介绍与文件上传
-
前言:django开发过程中,有2个文件夹(也即:目录)比较特殊:static文件夹(目录)、media文件夹(目录)。
- static目录:我们项目自己用到的文件(css、js、项目图片、插件),建议放在static目录下。
- media目录:用户自己上传的文件等资源,建议放在media目录下。要想用media目录,必须先配置启用它。
-
1.media的配置
- 1.1:在项目的同级目录下新建文件夹media
- 1.2:在setting中配置
- 1.1:在项目的同级目录下新建文件夹media
import os
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
- 1.3:urls中配置
from django.urls import path, re_path
from django.views.static import serve
from django.conf import settings
urlpatterns = [
re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}, name='media'),
]
- 2.上传混合数据(Form)
from django import forms
from app01.utils.bootstrap import BootStrapForm
class UpForm(BootStrapForm):
bootstrap_exclude_fields = ['img'] # img字段去除bootstrap样式
name = forms.CharField(label="姓名")
age = forms.IntegerField(label="年龄")
img = forms.FileField(label="头像")
def upload_form(request):
title = "Form上传"
if request.method == "GET":
form = UpForm()
return render(request, 'upload_form.html', {"form": form, "title": title})
form = UpForm(data=request.POST, files=request.FILES)
if form.is_valid():
# {'name': 'xwl', 'age': 123, 'img': <InMemoryUploadedFile: 图片 1.png (image/png)>}
# 1.读取图片内容,写入到文件夹中并获取文件的路径。
image_object = form.cleaned_data.get("img")
# media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)
media_path = os.path.join("media", image_object.name)
f = open(media_path, mode='wb')
for chunk in image_object.chunks():
f.write(chunk)
f.close()
# 2.将图片文件路径写入到数据库
models.Boss.objects.create(
name=form.cleaned_data['name'],
age=form.cleaned_data['age'],
img=media_path,
)
return HttpResponse("...")
return render(request, 'upload_form.html', {"form": form, "title": title})
- 3.上传混合数据(ModalForm)
- 3.1.models.py
class City(models.Model):
""" 城市 """
name = models.CharField(verbose_name="名称", max_length=32)
count = models.IntegerField(verbose_name="人口")
# 本质上数据库也是CharField,自动保存数据。
img = models.FileField(verbose_name="Logo", max_length=128, upload_to='city/')
- 3.2:定义ModelForm
from app01.utils.bootstrap import BootStrapModelForm
class UpModelForm(BootStrapModelForm):
bootstrap_exclude_fields = ['img']
class Meta:
model = models.City
fields = "__all__"
- 3.3:视图函数
def upload_modal_form(request):
""" 上传文件和数据(modelForm)"""
title = "ModelForm上传文件"
if request.method == "GET":
form = UpModelForm()
return render(request, 'upload_form.html', {"form": form, 'title': title})
form = UpModelForm(data=request.POST, files=request.FILES)
if form.is_valid():
# 对于文件:自动保存;
# 字段 + 上传路径写入到数据库
form.save()
return HttpResponse("成功")
return render(request, 'upload_form.html', {"form": form, 'title': title})