如何在未提交

时间:2015-09-25 13:57:32

标签: python django django-forms django-views

我是Django-python的新手,并尝试构建一个单页python-django网站,该网站将表单值提交给自己。但是最初没有提交表单时如何处理.get方法?

形式:

<form id="filters" action="{% url 'myapp:index' %}" method="GET">
{% csrf_token %}
<label><input type="checkbox" name="abc" value="abc" checked>Include abc</label>
<label><input type="checkbox" name="pqr" value="pqr" checked>Include abc</label>
<label><input type="checkbox" name="xyz" value="xyz" checked>Include abc</label>
<input type="submit" value="Submit">
</form>

Views.py:

from django.shortcuts import render

def index(request):
    try:
        abc = request.GET['abc']
        context = {'abc':abc}
    except (KeyError):
        raise
    else:
        return render(request, 'myapp/index.html', context)

现在,当我最初为myapp打开索引页面时,它会引发

  

MultiValueDictKeyError

我假设是因为最初没有设置复选框。

如果我将abc = request.GET [&#39; abc&#39;]更改为

abc = request.GET.get['abc']

提出:

  

类型错误
  &#39; instancemethod&#39;对象没有属性&#39; getitem &#39;

回溯:

                response = middleware_method(request, callback, callback_args, callback_kwargs)
                if response:
                    break
        if response is None:
            wrapped_callback = self.make_view_atomic(callback)
            try:
                            response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
            except Exception as e:
                # If the view raised an exception, run it through exception
                # middleware, and if the exception middleware returns a
                # response, use that. Otherwise, reraise the exception.
                for middleware_method in self._exception_middleware:
                    response = middleware_method(request, e)

坚持并且无法理解这些错误。

我可以像在PHP中那样执行if(!isset($ _ POST [&#39; submit&#39;])),以便在按下提交之前不会提交我的python脚本吗?

1 个答案:

答案 0 :(得分:2)

改变它

$9772385$,$3005A$
$99827837$,$3005A$

为:

abc = request.GET.get['abc']

并且,检查是否是GET方法:
使用:

abc = request.GET.get('abc')

Request Method

的文档