[Solved]-Django: login_required on ajax call


Instead of :

if not request.user.is_authenticated():
   return HttpResponseRedirect('/accounts/login')

return json response :

if request.user.is_authenticated():
    ## write your code...
    jsonr = json.dumps({ 'authenticated': True })
    return HttpResponse(jsonr, mimetype='application/json')
    jsonr = json.dumps({ 'authenticated': False })
    return HttpResponse(jsonr, mimetype='application/json')

And At your ajax success response , if not authenticated then redirect to login using windows.location .

OR you can write decorator :
Django authentication and Ajax – URLs that require login


When I want to check that when an Ajax call is made the user is logged in, here is what I use:

from functools import wraps
from django.core.exceptions import PermissionDenied

def ajax_login_required(view):
    def wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated():
            raise PermissionDenied
        return view(request, *args, **kwargs)
    return wrapper

raise PermissionDenied will cause a 403 status code to be returned to the client. Otherwise, if you use the @login_required decorator or perform manually a redirect to a form, what the Ajax call sees as a response is something that makes sense to a human being but not something that makes sense to an Ajax call.



I am not sure whether it’s an elegant solution but I made it to work as suggested by Priyank Patel

        var button = this;
                 type: "POST",
                 url: "{% url 'like' %}",
                 data: {'tutorial_id': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
                 dataType: "json",
                 success: function(json) {
                    if(json.not_authenticated) {

                    else {
                  error: function(rs, e) {


def like(request):
    response_dict = {}
    if request.user.is_authenticated():
        if request.method == 'POST':
            if not something:
                response_dict.update({'message': "Requested" })
                response_dict.update({'message': "You have already requested" })

        return HttpResponse(simplejson.dumps(response_dict),
        response_dict.update({'message': "Login please",'not_authenticated':True  })
        return HttpResponse(simplejson.dumps(response_dict),

Leave a comment