Django create添加数据后会返回新添加的数据行的queryset对象。从而获取自增id
应用场景:添加新随笔之后,将根据自增id,添加文章详细表和文章标签关系表
一对一关系的外键反向查询:
obj = models.UserInfo.objects.filter(username='sw').first() print(obj.blog.site) - 对于Form组件错误信息 { __all__: [错误1,错误2] user: [错误1,错误2] password: [错误1,错误2] } # 获取整体错误信息 - 后台 print(obj.errors['__all__']) print(obj.errors[NON_FIELD_ERRORS]) - 模板 { { obj.non_field_errors }} PS: 为某个字段添加异常 self.add_error('字段名称',错误异常对象) ajax提交请求时携带CSRF的3种方法:{% csrf_token %} 在网页中生成一个input标签隐藏起来 其value值为随机字符串,name为csrfmiddlewaretoken
{ { csrf_token }} 直接在网页中生成一个随机字符串显示出来
1 var csrf=$('input[name="csrfmiddlewaretoken"]').val()
data:{'csrfmiddlewaretoken':csrf} 2 data:{'csrfmiddlewaretoken':'{ { csrf_token }}'}
3 var token=$.cookie('csrftoken')
headers:{'X-CSRFToken':token} 博客文章内容:可以加css标签等,在用户上传内容是要过滤script关键字(beautifulsoup) <p>{ { article.content|safe }}</p>
路由匹配:
url(r'^(?P<site>\w+)/(?P<type>((tag)|(classfiy)|(datetime)))/(?P<typename>\w+-*\w*).html$',views.home,name='filter'), 给url设置别名可以不用从上到下匹配url,直接找到对应的url正则 给参数设置别名,可以在后台快速准确的找到不同参数(**kwargs) ((tag)|(classfiy)|(datetime))这个正则对应的是3个参数的'或'的关系
#自定义第三张表:自己反向关联article_tag表
all_count = models.article.objects.filter(blog=blog,article_tag__tag_id=typename).count()#通过M2M字段:直接通过m2m字段名从article表跨到tag表里 v=models.article.objects.filter(blog=blog,tags__id=typename)
通过年月在数据库查找
方法一: all_count = models.article.objects.filter(blog=blog,create_time__startswith=typename).count()方法二: all_count=models.article.objects.filter(blog=blog).extra(where=['strftime("%%Y-%%m",create_time)=%s'],params=[typename,]).count()通过年月对数据表进行分组:
sqlite数据库: select={'month':'strftime("%%Y-%%m",create_time)'} date_list=models.article.objects.filter(blog=blog).extra(select=select).values('month').annotate(num=Count('aid')) mysql 数据库 select = {'month': 'date_format(create_time,"%%Y-%%m")'} date_list = models.article.objects.filter().extra(select=select).values('month').annotate(num=Count('aid'))
将某操作添加为事务,原子性操作:
from django.db import transaction
with transaction.atomic():应用:
1 def up(request): 2 username=request.session.get('username') 3 status = { 'msg': '', 'type': None} 4 if username: 5 obj=models.user.objects.filter(nickname=username).first() 6 type=request.POST.get('type') 7 8 if type=='Y': 9 id = request.POST.get('id')10 try:11 from django.db import transaction12 with transaction.atomic():13 models.updown.objects.create(article_id=id,user_id=obj.uid,type=True)14 models.article.objects.filter(aid=id).update(up_count=F('up_count')+1)15 status['msg']='点赞成功'16 status['type']='True'17 return HttpResponse(json.dumps(status))18 except Exception as e:19 if models.updown.objects.filter(article_id=id,user_id=obj.uid,type=True).first():20 status['msg']='您已经点过赞了'21 return HttpResponse(json.dumps(status))22 else:23 status['msg']='您已经点过踩了,不能点赞了'24 return HttpResponse(json.dumps(status))25 else:26 id = request.POST.get('id')27 try:28 from django.db import transaction29 with transaction.atomic():30 models.updown.objects.create(article_id=id,user_id=obj.uid,type=False)31 models.article.objects.filter(aid=id).update(dowm_count=F('dowm_count')-1)32 status['msg'] = '点踩成功'33 status['type'] = 'False'34 return HttpResponse(json.dumps(status))35 except Exception as e:36 if models.updown.objects.filter(article_id=id,user_id=obj.uid,type=False).first():37 status['msg']='您已经点过踩了'38 return HttpResponse(json.dumps(status))39 else:40 status['msg']='您已经点过赞了,不能点踩了'41 return HttpResponse(json.dumps(status))42 else:43 status['msg']='请先登录'44 return HttpResponse(json.dumps(status))
删除用户的session(浏览器端)key=request.session.session_keyrequest.session.delete(key)
删除用户的session(数据库端和浏览器端)
from django.contrib.sessions.backends.db import SessionStore as DatabaseSessionsession = DatabaseSession()session.clear()session.delete(session.session_key)request.session.flush()应用:用户退出
自定义博客主题:{% block css %} <link rel="stylesheet" href="/static/css/theme/{ { dict.blog.theme }}.css">{% endblock %}