2

I want to get values from a form with 'GET' method and perform an operation with it. Now, my html is like this:

<form action="{% url 'myman' %}">
    <input type='hidden' name='agname' maxlength='300' value='{{mac.user.username}}' />
    <input  type='text'  name='amount' maxlength='300' required />
    <input type="submit" value="Send" />
</form>

The views is like this:

@login_required
def myman(request):

    yoname=request.GET.get('agname')
    print yoname  # did this to see the value in terminal, debugging purposes
    damount = request.GET.get('amount')
    print damount  # did this to see the value in terminal, debugging purposes

    requested_decimal_amount=Decimal(damount)
    # other code follows
    return redirect('dashboard')

I got this error Cannot convert None to Decimal

In my terminal, the url is like this:

" GET example.com/main/agname=jesse&amount=200 HTTP/1.1"
None
None

I changed my views.py function to this:

@login_required
def myman(request):

    yoname=request.GET['agname']
    print yoname  # did this to see the value in terminal, debugging purposes
    damount = request.GET['amount']
    print damount  # did this to see the value in terminal, debugging purposes

    requested_decimal_amount=Decimal(damount)
    # other code follows
    return redirect('dashboard')

I got this error:

MultiValueDictKeyError at /main/

"'agname'"

In the terminal I got:

" GET example.com/main/agname=jesse&amount=200 HTTP/1.1"
jesse
200

For the second function, it returned the values but I don't get why it's giving me an error!

More on the error:

Request Method:     GET
Request URL:    http://127.0.0.1:8000/main/
Django Version:     1.11.5
Exception Type:     MultiValueDictKeyError
Exception Value:    
"'agname'"

Exception Location:     C:\Python27\Scripts\env\lib\site-packages\django\utils\datastructures.py in __getitem__, line 85
Python Executable:  C:\Python27\Scripts\env\Scripts\python.exe
Python Version:     2.7.11

In the console

[10/Oct/2017 20:57:13] "GET /main/ HTTP/1.1" 500 84654
jesse
200
[10/Oct/2017 21:04:30] "GET /main/?agname=jesse&amount=200 HTTP/1.1" 302 0
Internal Server Error: /main/
Traceback (most recent call last):
      File "C:\Python27\Scripts\env\lib\site-
   packages\django\core\handlers\exception.py", line 41, in inner
  response = get_response(request)
  File "C:\Python27\Scripts\env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
  response = self.process_exception_by_middleware(e, request)
 File "C:\Python27\Scripts\env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
   response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python27\Scripts\env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view
   return view_func(request, *args, **kwargs)
  File "C:\Python27\Scripts\env\Scripts\mana\manamainapp\views.py", line 456, in myman
    yoname=request.GET['agname']
  File "C:\Python27\Scripts\env\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__
     raise MultiValueDictKeyError(repr(key))
     MultiValueDictKeyError: "'agname'"

What am I missing?

smack
  • 922
  • 11
  • 21

2 Answers2

0

You should be explicit & define your form method;

<form action="{% url 'myman' %}" method="get">

With that, then your first method is correct for getting the parameters;

yoname = request.GET.get('agname', 'default value')

Don't forget, the second argument to get() provides a default if the key isn't in the dictionary.

However if you really like request.GET['key'] try to ensure the key exists because to reference a dictionary key explicitly causes a KeyError if it's not there, and your error (MultiValueDictKeyError) is a variation of that;

if request.GET.get('q'):
    q = request.GET['q']

I'd probably write it like;

@login_required
def myman(request):

    if 'agname' in request.GET:
        yoname = request.GET.get('agname')
    if 'amount' in request.GET:
        damount = request.GET.get('amount')
        requested_decimal_amount=Decimal(damount)

    return redirect('dashboard')

Have a read of this; https://html.com/attributes/form-method/

<form method=”GET”>

The method attribute of the form element tells the web browser how to send form data to a server. Specifying a value of GET means the browser will add the form contents to the end of the URL. This offers a number of advantages for simple forms. It allows the browser to cache the results of the form submission, and it also allows the user to bookmark the page once the form has been submitted. As such, GET is generally used for simple forms where security is not a concern.

Community
  • 1
  • 1
markwalker_
  • 12,078
  • 7
  • 62
  • 99
  • @YoYo Ok, post your full stacktrace because otherwise we're just guessing. Are you using `request.GET['agname']` or `request.GET.get('agname')`? – markwalker_ Oct 10 '17 at 19:50
  • I've tested both and I'm getting different errors which I listed above. – smack Oct 10 '17 at 19:53
  • Post your stacktrace. – markwalker_ Oct 10 '17 at 19:54
  • No, the stacktrace is the list of calls, files (including line numbers) and the line executed. Basically what you see in the console above your error. Please post that. – markwalker_ Oct 10 '17 at 20:03
  • Thanks. Now I still believe it's your use of `request.GET['key']` instead of `request.GET.get('key', 'default')` that's your problem. I've updated my answer to explain. Also, see here; https://stackoverflow.com/questions/23531030/multivaluedictkeyerror-in-django – markwalker_ Oct 10 '17 at 20:19
-1
" GET example.com/main/agname=jesse&amount=200 HTTP/1.1" 

Did you see one thing in request URL there is not any '?' symbol that denote later data as get parameter. So you did not get any data in request of django view.

You need to add method="GET" in form tag that will tell browser to use field data as GET parameter not as URL

Neeraj Kumar
  • 3,851
  • 2
  • 19
  • 41