[英]HTTP 500 Error with Django Ajax
我正在嘗試將Django與AJAX調用結合使用,即使沒有錯誤,它也給了我HTTP 500甚至是MultiValueDictKeyError。
我發送了3個變量:sendEmail,用戶名,錯誤
我能夠對3個變量使用request.POST,並獲得以下輸出:
sendEmail = True
用戶名= someUserName
錯誤=登錄
但是,返回的網頁帶有HTTP 500
View.py:
def loginUser(request):
username = ""
type = ""
logger = logging.getLogger('views.logger.login')
try:
username = request.POST['username'];
logger.info("User:" + username + " in Login Page")
except MultiValueDictKeyError:
logger.info("Cannot Identify User")
try:
type = request.POST['submit']
logger.info("User:" + username + " requests:" + type)
except MultiValueDictKeyError:
logger.info("Cannot Identify User's Request")
if(type=="Login"):
try:
username = request.POST['username']
password = request.POST['password']
logger.info("UserName:" + username + " is trying to login")
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
logger.info("User is active, and logged in")
return redirect('index.html')
else:
logger.info("User is not active, and will not be logged in")
return redirect('disabled.html')
else:
logger.info("User:" + username + " is not valid");
context = {'Status': "Please sign in", 'Error': "Invalid", 'username':username}
return render(request, 'webapp/login.html', context)
except MultiValueDictKeyError:
logger.info("The user have missing forms")
context = {'Status': "Please sign in", 'Error': "Null"}
return render(request, 'webapp/login.html', context)
except Exception as e:
context = {'Status': "Please sign in", 'Error': "Null"}
return render(request, 'webapp/register.html', context)
logger.error("Error occured in Registering user");
logger.error("Error:" + str(e.args))
elif(type == "Register"):
logger.info("Redirecting user to Register Page")
return redirect('/webapp/register.html')
else:
logger.info("Startup Login Page");
context = {'Status': "Please sign in", 'Error': "Null"}
return render(request, 'webapp/login.html', context)
def ajax_sendMail(request):
logger = logging.getLogger('views.logger.sendEmail')
sendEmail = request.POST['email']
username = request.POST['username']
error = request.POST['error']
logger.info("Sending email to admins, sendEmail:" + sendEmail + ", username:" + username + ", error:" + error)
if(sendEmail == "true"):
mail_admins("User:" + username + " failed to " + error, "The time of error is at:" + datetime.datetime.now())
return HttpResponse("Success in Sending Email")
login.html:
<!DOCTYPE html>
<html>
<head>
<!-- Load css -->
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'WebApp/bootstrap-3.2.0-dist/css/bootstrap.min.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'WebApp/login.css' %}"/>
<title> WebStats Login </title>
</head>
<body>
<!-- Load javascripts -->
{% load staticfiles %}
<script type="text/javascript" src="{% static 'WebApp/jquery-2.1.1.min.js' %}"></script>
<script type="text/javascript" src="{% static 'WebApp/login.js' %}"></script>
<script type="text/javascript" src="{% static 'WebApp/bootstrap-3.2.0-dist/js/bootstrap.min.js' %}"></script>
<!-- Variables that we pass to javascript -->
<script type="text/javascript">
var errorMessage = "{{ Error }}";
var username = "{{ username }}";
</script>
<!-- Inputs and Buttons -->
<div class="container">
<form class="form-signin" role="form" action="{% url 'WebApp:login'%}" method="post">
{% csrf_token %}
<h2 class="form-signin-heading">{{ Status }}</h2>
<input type="username" id="username" name="username" class="form-control" placeholder="User Name" autofocus>
<input type="password" id="password" name="password" class="form-control" placeholder="Password">
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit" value="Login" name="submit" id="login">Sign in</button>
<button class="btn btn-lg btn-primary btn-block" type="submit" value="Register" name="submit" id="register">Register</button>
</form>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Error during Sign In</h4>
</div>
<div class="modal-body">
<p> Possible Reasons: </p>
<ol>
<li> Wrong Username or Password </li>
<li> User does not exist </li>
<li> Login Server is down </li>
<li> Account is Disabled </li>
<li> Check your internet cable </li>
<li> Programming error done by the Tool Owner </li>
<br>
<form>
<button type="button" id="sendErrorEmail" value="send" class="btn btn-danger" data-dismiss="modal"> Report Problem </button>
</ol>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
url.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth.views import logout
from WebApp import views
urlpatterns = patterns('',
url(r'^index', views.index, name='index'),
url(r'^login', views.loginUser, name='login'),
url(r'^logout', views.logoutUser, name='logout'),
url(r'^register', views.registerUser, name='register'),
url(r'^sendMail', views.ajax_sendMail, name='sendMail'),
)
login.js:
var main = function()
{
if(errorMessage == "Invalid")
{
$('#myModal').modal("show");
}
else
{
$('#myModal').modal("hide");
};
$("#sendErrorEmail").click(function(event)
{
var csrftoken = getCookie('csrftoken');
event.preventDefault();
$.ajax(
{
type:"POST",
url:"sendMail/",
data:{
'email': "true",
'error': "login",
'username' : username,
'csrfmiddlewaretoken':csrftoken
}
});
$('#myModal').modal("hide");
return false;
});
};
//To get the csrf token
function getCookie(name)
{
var cookieValue = null;
if (document.cookie && document.cookie != '')
{
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
{
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '='))
{
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$(document).ready(main);
我能夠成功發送AJAX POST調用,並且在函數Ajax_sendEmail的views.py中,我能夠獲取數據。 這是記錄器的詳細信息:
2014-09-04 16:04:20,901 [INFO] views.logger.login: User:adfafasdfa requests:Login
2014-09-04 16:04:20,901 [INFO] views.logger.login: UserName:adfafasdfa is trying to login
2014-09-04 16:04:21,124 [INFO] views.logger.login: User:adfafasdfa is not valid
2014-09-04 16:04:22,095 [INFO] views.logger.sendEmail: Sending email to admins, sendEmail:true, username:adfafasdfa, error:login
我能夠獲取sendEmail,用戶名和錯誤,但是它仍然調用HTTP 500 MultiValueDictKeyError。
MultiValueDictKeyError at /webapp/sendMail/
"'email'"
Request Method: GET
Request URL: http://127.0.0.1:8000/webapp/sendMail/
Django Version: 1.6.5
Exception Type: MultiValueDictKeyError
Exception Value:
"'email'"
Exception Location: C:\Python27\lib\site-packages\django\utils\datastructures.py in __getitem__, line 301
Python Executable: C:\Python27\python.exe
Python Version: 2.7.6
有誰知道為什么會這樣? 很奇怪...
更奇怪的是chrome inspect element工具,
Chrome Inspect Element工具的屏幕截圖:
它說這是POST,但是,當您進入內部時:
它顯示了一個
我不知道!
:)
確實,您的代碼看起來不錯。
您是否可能兩次調用了“ sendMail /” URL? 一次使用“ POST”(實際上是通過),一次使用其他地方的GET
?
我建議亂丟ajax_sendMail()
函數,同時調用logger(當然只是暫時的),以確切地看到何時引發異常,以及是否由於某種原因可能兩次調用該視圖。
也可以在ajax_sendMail()
正文的第一行中添加if request.method == 'POST':
條件。 當有可能密鑰不存在時request.POST.get('some_key', default_if_not_existing)
執行request.POST.get('some_key', default_if_not_existing)
總是一個好主意。 這不能解決您的問題,但可能有助於調試。
在您的settings.py文件中,將DEBUG值更改為DEBUG = True。 它將為您提供發生問題的堆棧跟蹤。 如果DEBUG = True,不要認為需要使用chrome檢查工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.