2

I have this decorator to check that the user is logged in and the account is activated.

def activation_required(func):
    """
    checks if user is registered logged in and activated
    """
    def decorator(request, *args, **kwargs):
        if request.user and request.user.is_authenticated():
            try:
                user = request.user
                if user.active:
                    return func(request, *args, **kwargs)
                else:
                    messages.add_message(request, messages.ERROR, "not activated!")
                    return HttpResponseRedirect(reverse('home'))
            except Exception as e:
                return HttpResponseServerError(repr(e))
        else:
            return HttpResponseRedirect(reverse('home'))
    return decorator

Instead of HttpResponseRedirect I would like to return an ajax error with a message. Is this possible? How?

function postData(url){
    var ajax_data = {
        message: "",
        return_val: ""
    };
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: ajax_data,
        success:function(data){
            alert('ok');
        }, // success
        error: function(data){
            alert(data.message); // <- this should run if user is not activated
        } // error
    }); // ajax
}
xpanta
  • 8,124
  • 15
  • 60
  • 104
  • 1
    I think this question would help you [create a json response]( http://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python) – 吕祥钊 Mar 14 '15 at 09:12

1 Answers1

3

Add this import:

from django.http import HttpResponse

and then, instead of an HttpResponseRedirect, return this:

return HttpResponse('Your message here', status=401)

I dont know enough about all javascript frameworks or browsers, but you might need to add in a content length, which instead of the above, you would do this:

response = HttpResponse('Your message here', status=401)
response['Content-Length'] = len(response.content)
return response
Titus P
  • 959
  • 1
  • 7
  • 16