未提交表单时如何使用django中的get方法处理表单元素

How to handle form elements with get method in django when form in not submitted

我是 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['abc'] 更改为

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

它提出:

TypeError
'instancemethod' object has no attribute 'getitem'

回溯:

                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['submit'])) 这样的事情吗,这样我的 python 脚本在按下提交之前不会提交?

改变它

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

至:

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

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

if request.method == 'GET':

Request Method

的文档