MultiDict错误Django

时间:2017-12-07 12:18:43

标签: python ajax django

我正在使用Django并试图通过使用AJAX获得响应。我有两种形式,第一种形式工作得很好。虽然我在第二种形式的处理中使用了相同的逻辑,但效果不佳。

models.py

class AskMe(models.Model):
    name = models.CharField(max_length=1000)

views.py

def AskMeQ(request):
    if request.method == POST:
        name = request.POST['name']

        AskMe.objects.create(name=name)

urls.py

url('r^askmeQ/$', views.AskMeQ)

ajax logic

$('.former').on('submit', '.ajaxform', function(event) {
    event.preventDefault();
    $.ajax({
        url: '/askmeQ/',
        type: 'POST',
        data: {name: $('#name').val(),
                csrfmiddlewaretoken: csrftoken
        }
    })
    .done(function() {
        console.log("success");
        $('.formset').slideToggle(400)
        });
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });
});

ERROR

Traceback:

File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
  77.             list_ = super().__getitem__(key)

During handling of the above exception ('name'), another exception occurred:

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/pc/Django_Projects/vikas/vikas/views.py" in askmeQ
  40.         name = request.POST['name']

File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
  79.             raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /askmeQ/
Exception Value: 'name'

我上面使用的逻辑曾用于以前的所有形式,但在这里它给我一个错误。
SQLite3表已创建为projectname_model.name

我该如何纠正?

1 个答案:

答案 0 :(得分:1)

似乎该名称未随请求一起发布。因此,POST会引发错误,因为该密钥不会成为def AskMeQ(request): if request.method == POST: name = request.POST.get('name') if name: AskMe.objects.create(name=name) # else: # error condition handling 字典的一部分。

要更正此问题,请将代码更改为:

.limited-string {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 90%;
}