[英]Django, how to force return ajax error?
我有這個裝飾器來檢查用戶是否已登錄並激活了帳戶。
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
}
添加此導入:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.