我有這個簡單的Like按鈕與@csrf_exempt
使用時效果很好:如何在Django的ajax POST中返回新的csrf標記?
模板
<p id="like_count"> {{ topic.likes }}</p>
<span data-type="topic" title="Like"> {% csrf_token %}
<i class="fa fa-thumbs-up" id="liket" name="{{topic.id}}">
阿賈克斯
$(function(){
$('#liket').click(function(){
$.ajax({
type: "POST",
url: "/like/",
data: {
'topic_id': $(this).attr('name'),
'csrfmiddlewaretoken': '{{csrf_token}}'
},
success: tlikeSuccess,
dataType: 'html'
});
});
});
function tlikeSuccess(data, textStatus, jqXHR)
{
$('#like_count').html(data);
}
和看法:
#@csrf_exempt
def topic_like(request):
args = {}
if request.method == 'POST':
user = request.POST.get('user')
lu= request.user #User.objects.get(username= user)
topic_id = int(request.POST.get('topic_id'))
try:
liked_topic = Topic.objects.get(id = topic_id)
except:
liked_topic = None
if TopicLike.objects.filter(liker=request.user.id, topic=topic_id).exists():
liked_topic.likes -=1
liked_topic.save()
TopicLike.objects.filter(topic=topic_id, liker=request.user.id).delete()
else:
liked_topic.likes +=1
liked_topic.save()
newliker = TopicLike(topic=topic_id, liker=request.user.id)
newliker.save()
#args.update(csrf(request))
args['likes'] = str(liked_topic.likes)
return render(request, 'ajax_like.html', args)
但是我不不喜歡這種忽略CSRF的解決方法,就像我一樣噸可能是脆弱的。 另一方面,我無法設法將新的CSRF令牌返回給模板,所以我感謝您將CSRF集成到此按鈕中的提示。
[Django文檔](https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax)建議在標題中提供csrf標記,而不是在發佈數據中提供。 – Alasdair
@阿拉斯代爾請給我一個完整的答案。我不知道如何應用文檔的建議。 – Jand
我認爲文檔非常清晰。你嘗試了什麼?你覺得缺少什麼?你不明白哪一部分? – Alasdair