目录
前端展示
路由:
数据库字段:
函数视图:
前端展示
{% extends "index/index.html" %}{% block content %}<div class="container"><input type="button" id="btnAdd" value="上传荣耀" class="btn btn-success"></div><div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"><div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><spanaria-hidden="true">×</span></button><h4 class="modal-title" id="myModalLabel">上传荣誉</h4></div><div class="modal-body"><form method="post" enctype="multipart/form-data">{% csrf_token %}{% for field in form %}{{ field }}{% endfor %}<div class="modal-footer"><button type="button" class="btn btn-warning" data-dismiss="modal">关闭</button><button type="submit" class="btn btn-success">上传</button></div></form></div></div></div></div><div class="container"><div class="col-xs-12" style="padding-top: 20px">{% for data in queryset %}<div class="col-xs-4"><h3>{{ data.title }}</h3><a href="/{{ data.img }}/"><img src="/{{ data.img }}/" width="350px" height="200px"></a></div>{% endfor %}</div></div>
{% endblock %}{% block js %}<script>$(function () {bindBtnAdd();})function bindBtnAdd() {$("#btnAdd").click(function (){$("#myModal").modal("show")})}</script>
{% endblock %}
路由:
from django.views.static import serve
from django.urls import path, re_path
re_path(r"^media/(?P<path>.*)$", serve, {"document_root": settings.MEDIA_ROOT})
数据库字段:
函数视图:
image.py
# -*- coding:utf-8 -*-
from django.shortcuts import render, redirect, HttpResponse
from demo_one import models
from datetime import datetime
from django import forms
import osclass ImageForm(forms.Form):title = forms.CharField(label="标题", widget=forms.TextInput(attrs={"class": "form-control", "autocomplete": "off"}))img = forms.FileField(label="图片")def image_list(request):queryset = models.Image.objects.all()if request.method == "GET":form = ImageForm()return render(request, "image/image_list.html", {"form": form, "queryset":queryset})form = ImageForm(data=request.POST, files=request.FILES)if form.is_valid():# 提交过来的图片对象image_object = form.cleaned_data.get("img")# 拼接路径,从media开始file_path = os.path.join("media", image_object.name).replace("\\", "/")with open(file_path, "wb") as file:# image_object.chunks() 获取到的是生成器对象for chunk in image_object.chunks():# 遍历结果为图片的字节file.write(chunk)models.Image.objects.create(title=form.cleaned_data["title"],times=datetime.now().strftime("%Y-%m-%d"),img=file_path)return redirect("/image/list/")return render(request, "image/image_list.html", {"form": form, "queryset":queryset})