[英]Django ajax GET 403 (Forbidden)
我的 Django 應用程序中有一個文章頁面和一個帶有 ajax 調用的加載更多按鈕。
問題是加載更多按鈕僅在用戶登錄到站點時才起作用。
如果匿名用戶單擊該按鈕,則它不起作用,並在 chrome 控制台中看到以下錯誤:
在 chrome 控制台的網絡選項卡中,我看到此錯誤:
但我不想識別單擊按鈕的用戶,並想向所有人顯示更多帖子!
ajax 調用是:
// Load more posts in the main page
$('.load-more').click(function () {
var card_count = $(".card-count").length;
$.ajax({
url: 'load-more',
method: 'GET',
data: {
"card_count": card_count,
},
success: function (data) {
// Append more articles to the article List
},
error: function (data) {
}
});
});
而負載更多的function為:
from rest_framework.decorators import api_view
@api_view()
def load_more(request):
card_count = request.GET.get("card_count")
no_more_article = False
all_articles = Article.objects.published()
article_count = all_articles.count()
try:
if article_count <= int(card_count) + 3:
no_more_article = True
articles = all_articles
else:
articles = all_articles.order_by('-publish')[:int(card_count) + 3]
except Article.DoesNotExist:
raise Article.DoesNotExist('No Articles')
serializer = ArticleSerializer(articles, many=True)
data = {
"no_more_article": no_more_article,
"serialized_obj": serializer.data,
}
return Response(json.dumps(data))
我做了一些搜索並嘗試了一些方法來傳遞csrf_token
或跳過它:
但仍然堅持這一點。
我怎樣才能擺脫這個錯誤?
謝謝你的幫助。
[編輯]:
根據@c.grey 的回答,我將這些裝飾器添加到視圖 function 的頂部,現在可以使用:
@api_view()
@authentication_classes([SessionAuthentication])
@permission_classes((AllowAny, ))
def load_more(request):
...
如果您使用的是重置框架裝飾器,那么您需要設置 authentication_classes 和權限。
@api_view()
@permission_classes((AllowAny, ))
def load_more(request):
----
閱讀此https://www.django-rest-framework.org/api-guide/views/#authentication_classes
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.