多字错误Djang

2024-09-30 01:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Django,并试图通过AJAX获得响应。我有两种形式,第一种很好。尽管我在第二个表单中使用了相同的逻辑,但它并不能很好地工作。在

模型.py

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

视图.py

^{pr2}$

网址.py

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

ajax逻辑

$('.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");
    });
});

错误

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。在

我该怎么更正?在


Tags: djangonameinpyresponserequestlibpackages
1条回答
网友
1楼 · 发布于 2024-09-30 01:22:36

似乎这个名字没有随请求一起发布。因此,name = request.POST['name']将抛出一个错误,因为密钥不是POSTdict的一部分

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

def AskMeQ(request):
    if request.method == POST:
        name = request.POST.get('name')
        if name:
            AskMe.objects.create(name=name)
        # else:
        #     error condition handling

相关问题 更多 >

    热门问题