编辑myprojrct/app01/templates/layout.html
<li><a href="/city/list/">城市列表(文件上传)</a></li>
添加路由
编辑myproject/myproject/urls.py
1. from app01.views import depart, pretty, user, admin, account, task, order, chart, upload, city 2.
#城市列表
path('city/list/', city.city_list),
path('city/add/', city.city_add),
创建视图函数myprojrct/app01/views.py/city.py
编辑myprojrct/app01/views.py/city.py
from django.shortcuts import render, HttpResponse, redirect
from app01 import models
from app01.utils.bootstrap import BootStrapModelForm
def city_list(request):
queryset = models.City.objects.all()
return render(request, 'city_list.html', {'queryset': queryset})
class UpModelForm(BootStrapModelForm):
bootstrap_exclude_fields = ['img']
class Meta:
model = models.City
fields = "__all__"
def city_add(request):
title = "新建城市"
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 redirect("/city/list/")
return render(request, 'upload_form.html', {"form": form, "title": title})
新建city_list.html
编辑myproject/app01/templates/city_list.html
{# 继承模板 #}
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div style="margin-bottom: 10px">
<a class="btn btn-success" href="/city/add/">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
新建城市
</a>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
城市列表
</div>
<!-- Table -->
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>LOGO</th>
<th>名称</th>
<th>人口</th>
</tr>
</thead>
<tbody>
{% for obj in queryset %}
<tr>
<th>{{ obj.id }}</th>
<td>
<img src="/media/{{ obj.img }}" style="height: 80px;">
</td>
<td>{{ obj.name }}</td>
<td>{{ obj.count }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
upload_form.html
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{ title }}</h3>
</div>
<div class="panel-body">
{# novalidate去除浏览器的错误提示 #}
<form method="post" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}</label>
{{ field }}
{# {{ field.errors }}错误信息是一个列表[错误1,错误2,错误3...], {{ field.errors.0 }}只取第一个错误1 #}
<span style="color: red;">{{ field.errors.0 }}</span>
{# <input type="text" class="form-control" placeholder="姓名" name="user"> #}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div>
</div>
</div>
{% endblock %}


若上传的图片文件名一样,modelform会自动在文件名后加一串随机字符,保存到数据库中,不用担心文件重名问题