【问题标题】:Django ajax GET 403 (Forbidden)Django ajax GET 403(禁止)
【发布时间】:2021-05-07 15:57:21
【问题描述】:

我的 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) {
        }
    });
});

而加载更多功能是:

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或跳过它:

This link & This link

但仍然坚持这一点。

我怎样才能摆脱这个错误?

感谢您的帮助。

[编辑]:

根据@c.grey 的回答,我将这些装饰器添加到视图函数的顶部,现在可以使用:

@api_view()
@authentication_classes([SessionAuthentication])
@permission_classes((AllowAny, ))
def load_more(request):
...

【问题讨论】:

  • 显示查看代码
  • 什么是 api_view
  • 什么是 api_view 及其来源

标签: python jquery django ajax


【解决方案1】:

如果您使用的是重置框架装饰器,那么您需要设置 authentication_classes 和权限。

@api_view()
@permission_classes((AllowAny, ))
def load_more(request):
   ----

阅读此https://www.django-rest-framework.org/api-guide/views/#authentication_classes

【讨论】:

  • 是的,成功了!我还添加了@authentication_classes([SessionAuthentication])装饰器!感谢您的帮助。
猜你喜欢
  • 2012-08-13
  • 2016-05-08
  • 1970-01-01
  • 2012-10-13
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多