python - ajax 中缺少 csrf 令牌
问题描述
我正在尝试构建一个 ajax 驱动的类似按钮,但 ajax 代码不起作用。
views.py
def like_button(request,postid):
postresult=get_object_or_404(post,id=postid)
if postresult.user_like.filter(id=request.user.id).exists():
postresult.user_like.remove(request.user)
else:
postresult.user_like.add(request.user)
noresdat=postresult.totallikes
response_data_to_dump={'success': True,'likes':noresdat}
data = json.dumps(response_data_to_dump)
return HttpResponse(data, content_type='application/json')
而模板如下:-
{% for p in result %}
<div class="SpriteContainer">
<a class="postlike" href="/like/{{ p.id }}"><img src="{%static "/images/icons/heart.png" %}"/></a>
<p class="nolike" style="display: inline-block;">{{ p.totallikes }}</p></div>
{% endfor %}
<script>
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
$(".postlike").click(function(e){
e.preventDefault();
var $this = $(this);
var url = $(this).data("action");
$.post(url, function(response){
if(response && response.success==true)
$this.next(".nolike").text(response.likes);
});
});
解决方案
CSRF 中间件和模板标签提供了针对跨站点请求伪造的易于使用的保护。(Django)。
并且在 MIDDLEWARE 设置中默认激活 CSRF 中间件。所以要么你必须提供 csrf 令牌,要么你必须从 CSRF 中排除该视图。视图基于类或函数。由于您使用的是基于函数的视图,因此您可以利用 [csrf_exempt]。1
from django.views.decorators.csrf import csrf_exempt,
@csrf_exempt
def like_button(request,postid):
推荐阅读
- javascript - 如何使用 javascript 将图像附加到特定的网格项
- r - 多目标优化约束问题:R
- permissions - 创建具有权限的静态角色的最佳实践
- sql - 基于第三个表连接两个表(SQLite)
- php - 我可以同时将数据从 php 保存到 json 和 MySQL 数据库吗?
- reactjs - React Context API 没有更新我的状态:做错了吗?(减速机部分)
- python - mplot3d 的 scatter 的“颜色”参数的全部容量是多少?
- javascript - 新手:不可能通过谷歌脚本和表单在邮件中获取我附加的 pdf
- javascript - JavaScript 表单输入
- java - 如何更改二维数组的大小?