图片上传+显示案例(续图片上传)


# -*- coding = utf-8 -*- # @Time : 2022/4/19 10:41 # @Author : 舒奇 # @File : city.py # @Software : PyCharm from django.shortcuts import render, 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})

class City(models.Model): """ 城市 """ name = models.CharField(verbose_name="名称", max_length=32) count = models.IntegerField(verbose_name="人口") # 本质上数据库也是CharField,自动保存数据,city目录下。 img = models.FileField(verbose_name="Logo", max_length=128, upload_to='city/')
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 %}
{% 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">
<form method="post" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}</label>
{{ field }}
<span style="color: red;">{{ field.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div>
</div>
</div>
{% endblock %}

浙公网安备 33010602011771号