为什么我在以下ajax代码中收到“500(内部服务器错误jQuery.min.js:4)”错误?

时间:2017-02-05 09:37:31

标签: jquery ajax django ajaxform

我正在尝试通过打开bootstrap登录模式并使用用户名和密码填写用户来登录用户,但是我点击“登录”按钮的动作我在浏览器的控制台中收到以下错误消息:

500 (internal server error)

AJAX:

$('#loginForm').on('submit',function(e){
  e.preventDefault();
  $.ajax({
    type: "POST",
    url: "/librarysystem/login/",
    data: {
      'username':$("username").val(),
      'password':$("password").val(),
      csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
    },
    dataType: 'json',
    success: function(data){
      if (data.response) {
        alert("Invalid");
      }  
      else
        alert("Valid");
   }        
  });
});

urls.py:

from django.conf.urls import url
from .import views

urlpatterns = [
    url(r'^register/$',views.create_user),
    url(r'^$', views.index, name="Index"),
    url(r'^validate/$',views.validateForm),
    url(r'^article/$', views.article, name="Article"),
    url(r'^Login/$',views.loginUser, name="Login")
]

views.py:

from forms import signupForm
from django.http import JsonResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User    

def loginUser(request):
    data = {}
    if request.method == 'POST':
       username = request.POST['username']
       password = request.POST['password']
       user = authenticate(username=username,password=password);                
       if user is None:
            data['response'] = False
       else:
            data['response'] = True
    return JsonResponse(data)

2 个答案:

答案 0 :(得分:1)

发布有关错误响应的更多信息会很有帮助,例如

    $.ajax({
    type: "POST",
    url: "/librarysystem/login/",
    data: {
      //...
    },
    dataType: 'json',
    success: function(data){
      //...
    },
    error: function(jqXHR, status, err){
        alert(jqXHR.responseText);
    }
  });

BTW,我只是猜测Django的身份验证设置未正确配置可能会引发异常。

答案 1 :(得分:0)

更改以下两行

username = request.POST['username']
password = request.POST['password']

username = request.POST.get('username','')
password = request.POST.get('password','')