1

I have a page of articles and a Load More button with ajax call in my Django app.

The problem is that the Load More button works just when the user logged in to the site.

If an anonymous user clicks on the button, it doesn't work, and sees the error below in the chrome console:

enter image description here

In the network tab in chrome console I see this error:

enter image description here

But I don't want to identify the user who clicked the button and want to show more posts to everyone!

The ajax call is :

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

And the load more function is:

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))

I do some search and tried some ways to pass the csrf_token or skip it:

This link & This link

But still stuck on this.

How can I get rid of this error?

Thanks for your help.

[Edit] :

According to @c.grey 's answer, I added these decorators to the top of the view function and it works now:

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

1 Answers1

1

If you are using reset framework decorator then you need to set authentication_classes and permissions.

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

Read this https://www.django-rest-framework.org/api-guide/views/#authentication_classes

rahul.m
  • 5,572
  • 3
  • 23
  • 50