我试图向django视图发送一个请求,但它一直返回INTERNAL SERVER ERROR 500
。
我的ajax帖子:
$.ajax({
url : "/loginAction/",
type : "POST",
async : false,
data : {action:'loginAction',
email:email,
password:password},
success : function(response) {
$.niftyNoty({
type:"success",icon:"",title:"Login Successful. Redirecting....",container:"floating",timer:5000
});
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
$.niftyNoty({
type:"danger",icon:"",title:"Wrong Email OR Password",container:"floating",timer:5000
});
}
});
我的django观点:
def loginAction(request):
print "Its workjing"
if request.method == 'POST' and 'loginButton' in request.POST:
email = request.POST.get('email')
password = request.POST.get('password')
print email, password
return HttpResponse(json.dumps({}),content_type="application/json")
我的url.py
urlpatterns = [
url(r'^', views.loginPage, name='loginPage'),
url(r'^loginAction/', views.loginAction, name='loginAction')
]
ajax帖子没有触及django视图。它没有在控制台中打印Its working
。所以它不会返回对ajax调用的json响应。我也尝试了正常的形式后,但同样的结果。我用的是django 1.9.2。我搞不懂为什么会犯这个错误?
它返回以下错误代码:
Internal Server Error: /loginAction/
Traceback (most recent call last):
File "/home/manish/Desktop/admin_picknbox/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 158, in get_response
% (callback.__module__, view_name))
ValueError: The view login_app.views.loginPage didn't return an HttpResponse object. It returned None instead.
编辑: ajax标题:
jQuery(document).ready(function($){
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
有一天我遇到了这个错误,但后来我意识到返回内部服务器错误的页面与我想要返回的html页面同名。我刚刚更改了html页面的名称,我想返回,一切都很好
view函数并没有处理所有的情况,如果
if request.method == 'POST' and 'loginButton' in request.POST:
是False
,那么view函数不会返回任何内容,因此会出错。Python函数如果不使用显式的return
语句,将返回None
。编辑:
如果您的
print
语句甚至没有执行,那么您必须有来自django的403响应。在进行ajax调用时,需要传递csrf
令牌,以防止来自未知人员的攻击。Django将自动检查csrf
,但您需要将其作为数据的一部分传递:另外,您应该检查
"action" in request.POST
而不是"loginAction" in request.POST
。似乎您的url是问题所在,因为在错误中,虽然您转到了
/loginAction/
,但似乎调用了loginPage
视图。因此,尝试在每个regex的末尾添加$
,如下所示:因为看起来第一个regex
r'^'
捕获了任何url。相关问题 更多 >
编程相关推荐