Django,如何强制返回ajax错误?

时间:2015-03-14 08:36:50

标签: javascript python ajax django

我有这个装饰器来检查用户是否已登录并且帐户已激活。

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

而不是HttpResponseRedirect我想用消息返回ajax错误。这可能吗?怎么样?

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
}

1 个答案:

答案 0 :(得分:3)

添加此导入:

from django.http import HttpResponse

然后,而不是HttpResponseRedirect,返回:

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

我对所有javascript框架或浏览器都不太了解,但您可能需要添加内容长度,而不是上面的内容,您可以这样做:

response = HttpResponse('Your message here', status=401)
response['Content-Length'] = len(response.content)
return response