在Django中使用ajax保存数据不会工作

时间:2016-07-20 03:50:11

标签: javascript jquery python ajax django

我正在尝试使用javascript将数据从django-views保存到jquery $.ajax,但浏览器控制台会给我这个错误:

以下是我的javascript内容$.ajax

var url = $(this).attr('action');

     $.ajax({
     type: 'POST',
     url : url,
     dataType    : 'json',
     data:{
        firstname   :   $('#firstname').val(),
        lastname    :   $('#lastname').val(),
        gender      :   $('#gender').val(),
        birthdate   :   $('#bdate').val(),
        age         :   $('#age').val(),
        address     :   $('#address').val(),
        mobile_no   :   $('#mobile').val(),
        home_no     :   $('#home').val(),
        email       :   $('#email').val(),
        csrfmiddlewaretoken     :   $('input[name=csrfmiddlewaretoken]').val(),
     },
     success:function(data){
        $('.bvc-emp-list-item-result').html(data)
     },
});

这是我的views.py

def create_employee(request):
    if request.method == 'POST':
        firstname = request.POST['firstname']
        lastname = request.POST['lastname']
        gender = request.POST['gender']
        bdate = request.POST['bdate']
        age = request.POST['age']
        address = request.POST['address']
        home_no = request.POST['home_no']
        mobile_no = request.POST['mobile_no']
        email = request.POST['email']

        Employee.objects.create(
            firstname = firstname,
            lastname = lastname,
            gender = gender,
            bdate = bdate,
            age = age,
            address = address,
            mobile_no = mobile_no,
            home_no = home_no,
            email = email
        )

        # Get all employee from db.
        employees = Employee.objects.all()

        return render_to_response(
            'payroll/employee/employee-list-item.html', # template
            {'employees' : employees }, # context
            context_instance=RequestContext(request) # request
        )

如果你想查看我的urls.py,那就是。

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

app_name = 'payroll'
urlpatterns = [
    # ex: /payroll/employee/create/
    url(r'^employee/create/$', views.create_employee, name='create_employee')
]

我是WebDev的新手,Django请帮忙。

更新

控制台日志生成POST错误,现在添加了一个 XHR finished loading: POST "http://127.0.0.1:8000/payroll/employee/create/"

现在cmd生成此追溯

Internal Server Error: /payroll/employee/create/
Traceback (most recent call last):
  File "C:\Users\Web\Desktop\PyDev\projects\bvc_env\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__
    list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: 'bdate'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Web\Desktop\PyDev\projects\bvc_env\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Web\Desktop\PyDev\projects\bvc_env\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Web\Desktop\PyDev\projects\bvc_env\src\payroll\views.py", line 21, in create_employee
    bdate = request.POST['bdate']
  File "C:\Users\Web\Desktop\PyDev\projects\bvc_env\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
    raise MultiValueDictKeyError(repr(key))
django.utils.datastructures.MultiValueDictKeyError: "'bdate'"
[20/Jul/2016 13:10:35] "POST /payroll/employee/create/ HTTP/1.1" 500 18952

2 个答案:

答案 0 :(得分:0)

首先,您必须在Ajax请求调用中传递csrf标记,请参阅this

否则它将不允许您作为GET请求的POST请求,并且您的整个数据将来自request.GET而不是request.POST。这样做,尝试打印request.datarequest.post,并根据用途request.data['firstname']request.POST['firstname']检查数据的位置。

答案 1 :(得分:0)

根据@solarissmoke建议,我将request.POST['bdate']更改为request.POST['birthdate'],因为在js文件中,变量为birthdate而不是bdate

然后当我开始为日期解析时,Django跟踪给出了这个错误:

  

ValueError: time data 'November 28, 1989' does not match format   “%Y-%m-%d'

所以我根据python date format documentation更改了代码:

bdate =  datetime.datetime.strptime(request.POST['birthdate'], "%B %d, %Y") 

现在最后一个问题是render_to_response函数,因为在Django documentation中不推荐使用它,将来可能会弃用我使用最新版本django 1.9

return render_to_response(
            'payroll/employee/employee-list-item.html', # template
            {'employees' : employees }, # context
            context_instance=RequestContext(request) # request
        )

我用这段代码替换它:

return render(request,
            'payroll/employee/employee-list-item.html', 
            {'employees' : employees }
        )

在js文件中,我将数据类型值替换为html

现在工作正常。