MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models文件
import time
# 用于对文件重命名,还可以修改文件的保存路径
def image_upload_to(instance, filename):
return 'company/{}{}'.format(time.strftime("%Y%m%d%H%M%S"),filename)
# 建立与order表的关联
class Img(models.Model):
img_url = models.ImageField(verbose_name="现场照片",upload_to=image_upload_to)
project_id = models.ForeignKey(verbose_name="项目名称",to=Order,default=1,on_delete=models.CASCADE)
urls
# media配置——配合settings中的MEDIA_ROOT的配置,就可以在浏览器的地址栏访问media文件夹及里面的文件了
re_path(r'media/(?P.*)$' , serve, {'document_root': settings.MEDIA_ROOT}),
path('uploadImg//' , temp.uploadImg),
path('img/delete//' , temp.deleteImg),
imgUpload.html
{% extends 'layou.html' %}
{% block css %}
<style>
#img-upload{
display: none;
}
style>
{% endblock %}
{% block content %}
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3>上传图片h3>
div>
<div class="panel-body">
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{# 用于修改上传图片按钮的显示效果 #}
{# 隐藏原按钮,用jquery将时间给予修饰的按钮 #}
<input type="button" class="btn btn-lg btn-info" value="选择文件" id="upload_btn">
<span class="glyphicon glyphicon-arrow-right" aria-hidden="true"> span>
<input type="file" name="img" accept="image/*" id="img-upload">
<input class="btn btn-primary btn-lg " style="margin-top:5px" type="submit" value="确定上传">
form>
div>
<div class="panel-heading">
<h3>已上传图片h3>
div>
<div class="panel-body">
{% for item in imgs %}
<div class="col-md-4">
<img src="{{ item.img_url.url }}" width="350px" >
<a href="/img/delete/{{ item.id }}" type="button" class="btn btn-danger" style="margin-top:-55px ">删除a>
div>
{% endfor %}
div>
div>
div>
{% endblock %}
{% block js %}
{# 用于修改上传图片按钮的显示效果 #}
<script type="text/javascript">
$(function () {
$("#upload_btn").on("click",function () {
$("#img-upload").click()
})
})
script>
{% endblock %}
views文件
def uploadImg(request,oid):
objs = models.Img.objects.filter(project_id_id=oid)
if request.method == "POST":
obj = models.Order.objects.get(id=oid)
if request.FILES.get('img') is None:
return render(request, "imgUpload.html", {"imgs": objs})
img = models.Img(img_url=request.FILES.get('img'),project_id=obj)
img.save()
return render(request, "imgUpload.html",{"imgs":objs})
def deleteImg(request,nid):
img = models.Img.objects.get(id=nid)
id = img.project_id_id
img.delete()
return redirect("/uploadImg/{}/".format(id))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)