【发布时间】:2017-10-10 19:21:03
【问题描述】:
我想用 'GET' 方法从表单中获取值并使用它执行操作。现在,我的 html 是这样的:
<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>
意见是这样的:
@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')
我收到此错误Cannot convert None to Decimal
在我的终端里,url是这样的:
" GET example.com/main/agname=jesse&amount=200 HTTP/1.1"
None
None
我将views.py 函数更改为:
@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')
我收到了这个错误:
MultiValueDictKeyError at /main/
"'agname'"
在我得到的终端中:
" GET example.com/main/agname=jesse&amount=200 HTTP/1.1"
jesse
200
对于第二个函数,它返回了值,但我不明白为什么它给我一个错误!
关于错误的更多信息:
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
在控制台中
[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'"
我错过了什么?
【问题讨论】:
-
在你的 html 表单元素中不应该是 method='get' 吗?
-
即使没有说明方法,默认方法也是get。我在某处读过它
-
没有重复!我已经说明了原因。