MohitC
MohitC

Reputation: 4791

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

I am new to Django-python and trying to build a single page python-django website which submits form values to itself. But how to handle .get method when form is not submitted initially?

Form:

<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)

Now when I open index page initially for myapp, it raises

MultiValueDictKeyError

which I assume is because the checkboxes are not set initially.

If I change abc = request.GET['abc'] to

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

It raises:

TypeError
'instancemethod' object has no attribute 'getitem'

Traceback:

                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)

Stuck and not able to understand these errors.

Can I do something like if(!isset($_POST['submit'])) like in PHP, so that my python script is not submitted until submit is pressed?

Upvotes: 2

Views: 1628

Answers (1)

Paulo Pessoa
Paulo Pessoa

Reputation: 2569

Change it

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

to:

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

And, for check if is a GET method:
Use:

if request.method == 'GET':

Documentation of Request Method

Upvotes: 3

Related Questions