django-附件上传、media、extra、事务
1 普通上传
1.1 html
<form action="/index/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p><input type="text" name="user" id="user"></p>
<p><input type="file" name="myFile" id="file"></p>
<input type="submit">
</form>
1.2 views
def index(request):
if request.method == "POST":
print(request.POST)
print(request.FILES)
file_obj = request.FILES.get("myFile")
print(file_obj.name) with open(file_obj.name,"wb") as f:
for line in file_obj:
f.write(line) return HttpResponse("上传成功。")
return render(request, "index.html")
2 基于ajax实现
2.1 Html
<p><input type="file" name="myFile" id="file"></p>
{% csrf_token %}
<button>ajaxSend</button>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script>
$("button").click(function () {
var formdata = new FormData();
formdata.append("imgFile", $("#file")[0].files[0]);
formdata.append("csrfmiddlewaretoken", $("[name='csrfmiddlewaretoken']").val());
$.ajax({
url: "/upload_img/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
console.log(msg)
}
})
})
</script>
2.2 views
import os,json
def upload_img(request):
if request.is_ajax():
obj = request.FILES.get("imgFile")
img_path = os.path.join("static","img",obj.name)
with open(img_path,mode="wb") as f:
for chunk in obj.chunks():
f.write(chunk)
data = {
"status" : True,
"path" : img_path
}
return HttpResponse(json.dumps(data))
3 伪ajax上传
基于FormData
缺点:兼容性不好
优点:Ajax直接发送
伪Ajax,兼容性更好
iframe,天生局部刷新
form,天生整个页面刷新
3.1 html
<input type="text" placeholder="默认值看看刷新之后在不在" />
<form method="POST" target="uploadIframe" action="/upload_img2/" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user" />
<a class="add-pub-btn pub-icons">
上传
<input type="file" name="avatar" id="imgUrl" />
</a>
<input type="submit" value="提交" />
</form>
<iframe id="ifm" name="uploadIframe" onload="successCallback(this);" style="display: none;" ></iframe>
<div id="imgList"></div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script>
function successCallback(ths){
var response = ths.contentWindow.document.body.innerHTML;
response = JSON.parse(response);
console.log(response);
var img = document.createElement('img');
img.src = "/" + response.data; $('#imgList').append(img);
}
</script>
3.2 views
def upload2(request):
return render(request,"iframe_upload.html") def upload_img2(request):
response = BaseResponse()
try:
obj = request.FILES.get("avatar")
img_path = os.path.join("static","img",obj.name)
with open(img_path,mode="wb") as f:
for chunk in obj.chunks():
for chunk in obj.chunks():
f.write(chunk)
except Exception as e:
response.msg = str(e)
else:
request.status = True
response.data = img_path
return HttpResponse(json.dumps(response.get_dict()))
4 上传按钮美化
4.1 css
<style>
.add-pub-btn {
width: 62px;
height: 31px;
line-height: 31px;
display: block;
text-align: center;
color: #fff;
font-size: 14px;
font-weight: 700;
margin-top: 5px;
cursor: pointer;
}
.pub-icons {
background: url(/static/img/bottom.png?v=2.8) no-repeat 0 0;
}
#imgUrl {
border: 0;
filter: alpha(opacity=0);
background: 0 0;
opacity: 0;
-moz-opacity: 0;
width: 62px;
height: 31px;
left: 5px;
top: 5px\9;
position: absolute;
cursor: pointer;
}
</style>
4.2 按钮设置
<a class="add-pub-btn pub-icons">
上传
<input type="file" name="avatar" id="imgUrl" />
</a>
5 图片预览
本图片的预览功能,主要利用html.js的FileReader进行实现的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
#avatar {
margin-top: 5px;
margin-bottom: 5px;
position: relative;
width: 100px;
height: 100px;
} #avatar_img, #file {
width: 100px;
height: 100px;
position: absolute;
left: 15px;
top: 0;
} #file {
opacity: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8" id="avatar">
<img src="default.png" class="img-thumbnail" id="avatar_img">
<input type="file" id="file">
</div>
</div>
</div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script type="text/javascript">
// 预览功能
$("#file").change(function () {
var choose_file = $("#file")[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(choose_file);
reader.onload = function () {
$("#avatar_img").attr("src", this.result)
}
});
</script> </body>
</html>
6 文件上传路径
6.1 配置
在settings中配置
MEDIA_ROOT=os.path.join(BASE_DIR,"blog","media")
MEDIA_URL="/media/"
在urls.py中配置
from django.views.static import serve
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
6.2 使用
<img src='/media/avatarDir/a.png'>
7 extra
有些情况下,Django的查询语法难以简单的表达复杂的 WHERE 子句,对于这种情况, Django 提供了 extra() QuerySet修改机制 — 它能在 QuerySet生成的SQL从句中注入新子句
extra可以指定一个或多个 参数,例如 select, where or tables. 这些参数都不是必须的,但是你至少要使用一个!要注意这些额外的方式对不同的数据库引擎可能存在移植性问题.(因为你在显式的书写SQL语句),除非万不得已,尽量避免这样做
# in sqlite:
article_obj=models.Article.objects
.filter(nid=1)
.extra(select={"standard_time":"strftime('%%Y-%%m-%%d',create_time)"})
.values("standard_time","nid","title")
print(article_obj)
# <QuerySet [{'title': 'MongoDb 入门教程', 'standard_time': '2017-09-03', 'nid': 1}]>
current_user = models.UserInfo.objects.filter(username=username).first() #当前用户
【每一步的分析过程】
1、models.Article.objects.all() #查出每一篇文章
2、models.Article.objects.all().filter(user=current_user) #查出当前用户的所有文章
3、models.Article.objects.all().filter(user=current_user).extra(select={"filter_create_date":"strftime('%%Y/%%m',create_time)"}).values_list("filter_create_date")
#查出当前用户的所有文章的create_time,并且只取出年份和月份
解决方案:使用extra方法
extra使用来进行过滤的,参数select必须等于一个字典(转成sql的where语句去执行,查出create_time,然后转换成自己格式化的时间)
4、models.Article.objects.all().filter(user=current_user).extra(select={"filter_create_date":"strftime('%%Y/%%m',create_time)"}).values_list("filter_create_date").annotate(Count("title"))
#按照查询出来的年份和月份进行分组,并且显示文章个数
8 事务使用
from django.contrib.auth import authenticate
with transaction.atomic():
models.ArticleUpDown.objects.create(user_id=user_id, article_id=article_id)
models.Article.objects.filter(nid=article_id).update(up_count=F("up_count") + 1)
django-附件上传、media、extra、事务的更多相关文章
- Django文件上传下载与富文本编辑框
django文件上传下载 上传 配置settings.py # 设定文件的访问路径,如:访问http://127.0.0.1:8000/media/就可以获取文件 MEDIA_URL = '/medi ...
- asp.net结合uploadify实现多附件上传
1.说明 uploadify是一款优秀jQuery插件,主要功能是批量上传文件.大多数同学对多附件上传感到棘手,现将asp.net结合uploadfiy如何实现批量上传附件给大家讲解一下,有什么不对的 ...
- ueditor调用其中的附件上传功能
ueditor实际上是集成了webuploader, 在做内容发布的时候想既有ueditor又有单独的附件上传按钮,这时再加载一个webuploader就显得过于臃肿了,单独利用ueditor的上传功 ...
- 基于MVC4+EasyUI的Web开发框架形成之旅--附件上传组件uploadify的使用
大概一年前,我还在用Asp.NET开发一些行业管理系统的时候,就曾经使用这个组件作为文件的上传操作,在随笔<Web开发中的文件上传组件uploadify的使用>中可以看到,Asp.NET中 ...
- 百度在线编辑器UEditor(v1.3.6) .net环境下详细配置教程之更改图片和附件上传路径
本文是接上一篇博客,如果有疑问请先阅读上一篇:百度在线编辑器UEditor(v1.3.6) .net环境下详细配置教程 默认UEditor上传图片的路径是,编辑器包目录里面的net目录下 下面就演示如 ...
- tp中附件上传文件,表单提交
public function tianjia(){ $goods=D('Goods'); if(!empty($_POST)){ if($_FILES['f_goods_image']['error ...
- 使用plupload做一个类似qq邮箱附件上传的效果
公司项目中使用的框架是springmvc+hibernate+spring,目前需要做一个类似qq邮箱附件上传的功能,暂时只是上传小类型的附件 处理过程和解决方案都需要添加附件,处理过程和解决方案都可 ...
- Dynamic CRM 2013学习笔记(十三)附件上传 / 上传附件
上传附件可能是CRM里比较常用的一个需求了,本文将介绍如何在CRM里实现附件的上传.显示及下载.包括以下几个步骤: 附件上传的web页面 附件显示及下载的附件实体 调用上传web页面的JS文件 实体上 ...
- playframework中多附件上传注意事项
playframework中多附件上传注意事项 2013年09月24日 play 暂无评论 //play版本问题 经确认,1.0.3.2版本下控制器中方法参数 List<File> fi ...
- JS实现多附件上传(asp.net)
前几天,用户提出一个需求-多附件上传,另外,每个上传文件要加一个别名,本人创新少,从网上收集了资料,稍微改写,满足了 客户的需求.在应用到程序之前,先做了个小测试,测试通过,小高兴,就记录下了这个小测 ...
随机推荐
- NB二人组(二)----归并排序
归并排序的思路: 归并算法程序(配合下图进行思考): def merge(li,low,mid,high): i = low j = mid + 1 ltmp=[] while i <= mid ...
- python基础===python自带idle的快捷键
Ctrl + [ Ctrl + ] 缩进代码Alt+3 Alt+4 注释.取消注释代码行Alt+5 Alt+6 切换缩进方式 空格<=>TabAlt+/ 单词完成,只要文中出现过,就可 ...
- PHY Linux 驱动
以太网 MAC(链路层)+PHY(物理层/RTL8201F,88E1111);集成型DM9000,RTL8139CP 由于网络数据传输量较大,不论是分开型还是集成型,通常会在MAC和PHY之间引入DM ...
- 虚拟机NAT网络设置
1. 虚拟机设置 2. 本地网络设置 3. 本地虚拟网卡设置 4. 安装虚拟机,设置网络为NAT方式即可访问外网.
- Nginx源码分析--数组(转)
原文地址:http://blog.csdn.net/marcky/article/details/5747431 备注:以下关于Nginx源码的分析基于淘宝开源项目Tengine. Nginx中对数组 ...
- php琐碎
1.类中的常量,可以用类来引用: class MyClass() { const SUCCESS ="success"; const FAIL ="fail"; ...
- 中文chrome font-size 10px,11px,12px,rem只为12px解决办法
问题来源: html { font-size: 10px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } .form-signin { max-wi ...
- Codeforces 821C Okabe and Boxes(模拟)
题目大意:给你编号为1-n的箱子,放的顺序不定,有n条add指令将箱子放入栈中,有n条remove指令将箱子移除栈,移出去的顺序是从1-n的,至少需要对箱子重新排序几次. 解题思路:可以通过把栈清空表 ...
- 推荐一个数据相关的网站tushare
推荐一个网站:tushare 使用方法如下: pip install tushare 我是使用pycharm直接安装的 抓取了浦发和光大的股票数据,并通过csv进行保存,和通过plt进行图片打印 im ...
- [Ext JS 4] MVC 应用程序框架
前言 大型客户端应用程序总是很难编写,很难组织和很难维护.随着功能的增加和更多的开发人员加入项目,对项目的控制也越来越困难了.Ext JS 4 提供了一个新的应用程序框架帮助组织代码. 模型 - 一组 ...