django高级之点赞、文章评论及上传文件
目录:
- 点赞
- 文章评论
- 上传文件
- 保留页面条件
一、点赞
1、所用技术:
- django model F查询
- js应用:$(function () {}); 为文件加载完成执行ready() 方法。等同于on时间,多实例,使用。
定时器方法:setInterval(方法,间隔多长时间(毫秒)执行一次)
var obj = setInterval(function () {
if(xxx <= 0){
clearInterval(obj); //结束执行
},100);
ps.setTimeout(表达式,延时时间)在执行时,是在载入后延迟指定时间后,去执行一次表达式,记住,次数是一次
- css应用:
position属性
值 | 描述 |
---|---|
absolute |
生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。 元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
fixed |
生成绝对定位的元素,相对于浏览器窗口进行定位。 元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
relative |
生成相对定位的元素,相对于其正常位置进行定位。 因此,"left:20" 会向元素的 LEFT 位置添加 20 像素。 |
static | 默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。 |
inherit | 规定应该从父元素继承 position 属性的值。 |
- 在Ajax操作时候,回调函数中的 $(this)已经不是原来的$(this)。需在外层函数声明。
2、应用代码:
前端:
<div>
<div>{{ row.title }}</div>
<div>{{ row.user.username }} 评论:{{ row.comment_count }}
<!--使用相对定位-->
<div style="display: inline-block;position: relative;">
赞:<a class="new-like" new-id="{{ row.id }}">{{ row.like_count }}</a>
</div>
</div>
</div>
<script src="/static/jquery-3.2.1.js"></script>
<script>
$(function () {
bindLikeEvent();
}); function bindLikeEvent() {
$('.new-like').click(function () {
// 获取当前新闻ID
var newId = $(this).attr('new-id');
var $this = $(this);
$.ajax({
url: '/do_like.html',
type: "POST",
data: {'newId': newId},
dataType: 'JSON',
success:function (arg) {
if(arg.status){
var origin = $this.text();
var count = parseInt(origin);
if(arg.code == 666){
$this.text(count - 1 );
showLikeCount($this,'-1'); }else if(arg.code == 999){
$this.text(count + 1 );
showLikeCount($this,'+1'); }
}else{
alert(arg.msg);
}
} })
})
} function showLikeCount($this,text) {
var fontSize = 5;
var top = 0;
var right = 0;
var opacity = 1; var tag = document.createElement('span');
// var tag = document.getElementById()
tag.innerText = text;
tag.style.position = "absolute";
// 默认大小
tag.style.fontSize = fontSize + "px";
tag.style.top = top + 'px';
tag.style.right = right + 'px';
tag.style.opacity = opacity;
$this.after(tag); // 定时器,没0.5s执行一次
var obj = setInterval(function () {
fontSize += 5;
top -= 5;
right -= 5;
opacity -= 0.1; tag.style.fontSize = fontSize + "px";
tag.style.top = top + 'px';
tag.style.right = right + 'px';
tag.style.opacity = opacity;
if(opacity <= 0){
clearInterval(obj);
tag.remove();
}
},100); }
</script>
后端:
import json
from django.db.models import F
from django.db import transaction
from utils.response import LikeResponse def do_like(request):
"""
点赞
:param request:
:return:
"""
response = LikeResponse()
try:
new_id = request.POST.get('newId')
# 当前登录用户ID
# uid = request.session.get('uid')
uid = 1 exist_like = models.Like.objects.filter(nnew_id=new_id,uuser_id=uid).count()
with transaction.atomic():
if exist_like:
models.Like.objects.filter(nnew_id=new_id, uuser_id=uid).delete()
models.News.objects.filter(id=new_id).update(like_count=F('like_count') - 1)
response.code = 666
else:
models.Like.objects.create(nnew_id=new_id,uuser_id=uid)
models.News.objects.filter(id=new_id).update(like_count=F('like_count') + 1)
response.code = 999
except Exception as e:
response.msg = str(e)
else:
response.status = True
return HttpResponse(json.dumps(response.get_dict()))
ps.response实例化
class BaseResponse(object):
def __init__(self):
self.status = False
self.data = None
self.msg = None def get_dict(self):
return self.__dict__ class LikeResponse(BaseResponse):
def __init__(self):
self.code = 0
super(LikeResponse,self).__init__() # obj = LikeResponse()
# print(obj.__dict__)
二、文章评论
1、所用技术
- python:
字典,列表,通过引用赋值,一个修改全部都改的特性
递归取值
2、应用
前端:
<h1>评论</h1>
{{ comment_html|safe }}
后端:
def build_comment_data(li):
dic = {}
for item in li:
item['children'] = []
dic[item['id']] = item result = []
for item in li:
pid = item['parent_id']
if pid:
dic[pid]['children'].append(item)
else:
result.append(item) return result def build_comment_tree(com_list):
"""
{'user': '银秋良1', 'children': [],content:'xxx'],
{'user': '银秋良2', 'children': [{'user': '型谱', 'children': [{'user': '银秋良', 'children': [], 'parent_id': 3, 'content': '你是流氓', 'id': 5}], 'parent_id': 1, 'content': '你个文盲', 'id': 3}], 'parent_id': None, 'content': '灌我鸟事', 'id': 1}
{'user': '银秋良3', 'children': [{'user': '详解', 'children': [], 'parent_id': 2, 'content': '好羡慕你们这些没脸的人呀', 'id': 4}], 'parent_id': None, 'content': '管我鸟事', 'id': 2} [
{'user': '银秋良', 'children': [], 'parent_id': 3, 'content': '你是流氓', 'id': 5}
] """
tpl = """
<div class="item">
<div class="title">{0}:{1}</div>
<div class="body">{2}</div>
</div>
"""
html = ""
for item in com_list:
if not item['children']:
html +=tpl.format(item['user'],item['content'],"")
else:
html +=tpl.format(item['user'], item['content'], build_comment_tree(item['children']))
return html def comment_list(request):
"""
获取多级评论列表
:param request:
:return:
"""
li = [
{'id': 1, 'user': '银秋良', 'content': '灌我鸟事', 'parent_id': None},
{'id': 2, 'user': '银秋良', 'content': '管我鸟事', 'parent_id': None},
{'id': 3, 'user': '型谱', 'content': '你个文盲', 'parent_id': 1},
{'id': 4, 'user': '详解', 'content': '好羡慕你们这些没脸的人呀', 'parent_id': 2},
{'id': 5, 'user': '银秋良', 'content': '你是流氓', 'parent_id': 3},
{'id': 6, 'user': '银秋良', 'content': '你冷库无情', 'parent_id': 5},
{'id': 7, 'user': '银秋良', 'content': '你才冷酷无情', 'parent_id': 4},
{'id': 8, 'user': '银秋良', 'content': '你无理取闹', 'parent_id': 4},
]
com_list = build_comment_data(li)
"""
{'user': '银秋良', 'children': [{'user': '型谱', 'children': [{'user': '银秋良', 'children': [], 'parent_id': 3, 'content': '你是流氓', 'id': 5}], 'parent_id': 1, 'content': '你个文盲', 'id': 3}], 'parent_id': None, 'content': '灌我鸟事', 'id': 1}
{'user': '银秋良', 'children': [{'user': '详解', 'children': [], 'parent_id': 2, 'content': '好羡慕你们这些没脸的人呀', 'id': 4}], 'parent_id': None, 'content': '管我鸟事', 'id': 2}
""" html = build_comment_tree(com_list) return render(request,'comment_list.html',{'comment_html':html}) def fetch_comment(request):
li = [
{'id': 1, 'user': '银秋良', 'content': '灌我鸟事', 'parent_id': None},
{'id': 2, 'user': '银秋良', 'content': '管我鸟事', 'parent_id': None},
{'id': 3, 'user': '型谱', 'content': '你个文盲', 'parent_id': 1},
{'id': 4, 'user': '详解', 'content': '好羡慕你们这些没脸的人呀', 'parent_id': 2},
{'id': 5, 'user': '银秋良', 'content': '你是流氓', 'parent_id': 3},
{'id': 6, 'user': '银秋良', 'content': '你冷库无情', 'parent_id': 5},
{'id': 7, 'user': '银秋良', 'content': '你才冷酷无情', 'parent_id': 4},
{'id': 8, 'user': '银秋良', 'content': '你无理取闹', 'parent_id': 4},
]
com_list = build_comment_data(li)
# 第一种选择
html = build_comment_tree(com_list)
return HttpResponse(html)
# 第二种选择,前端递归去生成
# return HttpResponse(json.dumps(com_list))
ps.使用方式:
返回给前端JavaScrip,由前端递归渲染。本例为服务器直接渲染返回
三、上传文件
1、所使用技术:
- js:
- 基于FormData
- 缺点,兼容性不好
- 优点,Ajax直接发送
- 伪Ajax,兼容性更好
- iframe,天生局部刷新
- form,天生整个页面刷新
2、应用:
前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" placeholder="默认值看看刷新之后在不在" />
<form method="POST" target="xxxxxx" action="/upload_img2/" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user" />
<a style="width: 60px;height: 30px;background-color: darkslateblue;color: white;display: inline-block;position: relative;">
上传
<input type="file" name="avatar" style="opacity: 0;position: absolute;left: 0;top:0;right: 0;bottom: 0;" />
</a>
<input type="submit" value="提交" />
</form>
<iframe id="ifm" name="xxxxxx" onload="successCallback(this);" style="display: none;" ></iframe>
<div id="imgList"></div>
<script src="/static/jquery-3.2.1.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> </body>
</html>
后端:
def upload_img2(request):
response = BaseResponse()
try:
user = request.POST.get('user')
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():
f.write(chunk)
except Exception as e:
response.msg = str(e)
else:
response.status = True
response.data = img_path
return HttpResponse(json.dumps(response.get_dict()))
四、保留页面条件
1、所用技术:
django request.GET.urlencode() 获取url.get方法
django from django.http.request import QueryDict 导入QueryDict方法
ps.POST,不要写action
2、应用:
前端:
list
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/add_host.html?{{ url_param }}">添加</a>
<ul>
{% for item in hosts %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
add
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST">
{% csrf_token %}
<input type="text" name="hostname" />
<input type="submit" value="提交" />
</form>
</body>
</html>
后端:
from django.http.request import QueryDict
def host_list(request):
print(request.GET,type(request.GET))
# request.GET._mutable = True obj = QueryDict(mutable=True)
obj['_zhaofengfeng'] = request.GET.urlencode() # page=10&id=1
url_param = obj.urlencode() hosts = ['c1.com','c2.com','c3.com']
return render(request,'host_list.html',{'hosts':hosts,'url_param':url_param}) def add_host(request):
if request.method == "GET":
return render(request,'add.html')
else:
url_params = request.GET.get('_zhaofengfeng')
host = request.POST.get('hostname')
url ="/host_list.html?"+url_params
return redirect(url)
django高级之点赞、文章评论及上传文件的更多相关文章
- 基于Ubuntu Server 16.04 LTS版本安装和部署Django之(三):设置上传文件夹权限(这里测试用完全共享)
基于Ubuntu Server 16.04 LTS版本安装和部署Django之(一):安装Python3-pip和Django 基于Ubuntu Server 16.04 LTS版本安装和部署Djan ...
- 使用django表单,使网页添加上传文件,并分析文件。
开发环境是: apache + python + django+ eclipse(开发环境) 欲达到目的: 在网页上,添加上传文件控件.然后读取csv文件,并分析csv文件. 操作步骤: django ...
- 【Django组件】KindEditor富文本编辑器上传文件,html样式文本,VUE异步提交数据(易懂版)
1:下载与配置 适合版本: python3 下载:http://kindeditor.net/down.php 文档:http://kindeditor.net/doc.php 将文件包放入stati ...
- Django学习——ajax发送其他请求、上传文件(ajax和form两种方式)、ajax上传json格式、 Django内置序列化(了解)、分页器的使用
1 ajax发送其他请求 1 写在form表单 submit和button会触发提交 <form action=""> </form> 注释 2 使用inp ...
- $Django ajax简介 ajax简单数据交互,上传文件(form-data格式数据),Json数据格式交互
一.ajax 1 什么是ajax:异步的JavaScript和xml,跟后台交互,都用json 2 ajax干啥用的?前后端做数据交互: 3 之前学的跟后台做交互的方式: -第一种:在浏览器 ...
- python自动化开发-[第二十二天]-bbs多级评论、点赞、上传文件
今日概要: 1.related_name和related_query_name的区别 2.through_fields的用途 3.django的事务提交 4.点赞的动画效果 5.多级评论的原理 6.上 ...
- Linux下开发python django程序(设置admin后台管理上传文件和前台上传文件保存数据库)
1.项目创建相关工作参考前面 2.在models.py文件中定义数据库结构 import django.db import modelsclass RegisterUser(models.Model) ...
- django + dropzone.js 上传文件
1.dropzone.js http://www.dropzonejs.com/ dropzone.js是一个可预览\可定制化的文件拖拽上传,实现AJAX异步上传文件的工具 2.dropzone.js ...
- Django之富文本编辑器kindeditor 及上传
1.什么是富文本编辑器 百度百科(https://baike.baidu.com/item/%E5%AF%8C%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8 ...
随机推荐
- jQuery实现HTML表格单元格的合并功能
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- HDU2717BFS
/* WA了12发简直不能忍! . 题意非常简单.从正整数a变为b有三种方法: +1,-1.*2 特殊情况一:a与b相等不须要搜索 特殊情况二:a>b时.结果必定是a-b不需搜 特殊情况三:比較 ...
- Mysql课后思考题
1.请简述数据库.表和数据库服务器之间的关系? 知识点数据库存储结构 一个数据库服务器可以管理多个数据库,通常情况下开发人员会针对每个应用创建一个数据库,为保存应用中实体的数据,会在数据库中创建多个表 ...
- day19<异常&File类>
异常(异常的概述和分类) 异常(JVM默认是如何处理异常的) 异常(try...catch的方式处理异常1) 异常(try...catch的方式处理异常2) 异常(编译期异常和运行期异常的区别) 异常 ...
- ios开发之--UIDocumentInteractionController的使用(实现更多分享服务)
最近在做项目的时候,碰到这样一个需求,就是本地生成pdf文件,然后本地打开,经过测试发现,pdf文件是无法保存到相册里面的,只能存到手机里面,鉴于苹果的存储机制,需要取出来,进行本地展示,可以直接传到 ...
- Loadrunner windows计数器
object (对象) Counters (计数器名称) Description (描述) 参考值 Memory Available Mbytes 可用物理内存数.如果该值很小(4MB或更小),则说明 ...
- ionic调用数据接口(post、解决 payload 问题)
$http({method:'POST', url:apiUrl, headers:{'Content-Type': 'application/x-www-form-urlencoded; chars ...
- centos6 安装 directAdmin
注:教程参考 https://bbs.aliyun.com/read/159390.html 这篇文章来操作就可以了 需要注意的地方是 1)directAdmin 需要一个纯净的环境,安装direct ...
- STM32学习之路之入门篇
2006年ARM公司推出了基于ARMV7架构的cortex系列的标准体系结构,以满足各种技术得不同性能要求,包含了A,R,M三个分工明确的系列 其中A系列面向复杂的尖端应用程序,用于运行开放式的复杂操 ...
- 说说GPIO.H(NUC131)
/**************************************************************************//** * @file GPIO.h * @ve ...