1. models.py
class Boss(models.Model):
name = models.CharField(verbose_name="姓名", max_length=64)
age = models.IntegerField(verbose_name="年龄")
img = models.CharField(verbose_name="头像", max_length=256)
这种写法需要在view_name.py文件中去处处理 待保存文件的路径问题, 并调用create方法.
media_file_path = os.path.join("media", image_object.name)
print(media_file_path)
f = open(media_file_path, mode="wb")
for chunk in image_object.chunks():
f.write(chunk)
f.close()
models.Boss.objects.create(
name = form.cleaned_data['name'],
age = form.cleaned_data['age'],
img = media_file_path,
class City(models.Model):
name = models.CharField(verbose_name="名称", max_length=64)
count = models.IntegerField(verbose_name="人口")
# 此处写成"FileField", 而不是"IntegerField", 这样FileField会多出upload_to='目录名'属性, 在入库时可快速将图片保存到该目录
logo = models.FileField(verbose_name="logo", max_length=256, upload_to='city/')
2. view_name.py
class UpModelForm(BootStrapModelForm):
class Meta:
model = models.City
fields = "__all__"
def upload_model_form(request):
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('成功')
可以看到这种写法非常简捷, 保存路径已在创建model时设置, 而保存数据只需form.save()即可.
3. 结果验证
- 保存路径: logo = models.FileField(verbose_name=”logo”, max_length=256, upload_to=’city/’)
- 如何保存: form.save()
4. 前置条件
配置media目录. (实际使用中, 由于目录位置等差异, 根据实际情调整.)
4.1 setting.py
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
4.2 urls.py 路由
from django.views.static import serve
from django.conf import settings
re_path(r'^media/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}, name='media'),
本站文章除单独注明外均为原创,本文链接https://bowmanjin.com/327,未经允许请勿转载。
请先
!