Skip to main content
 首页 » 编程设计

Python Django Dict 对象不可调用

2025年05月04日36lautakyan007

我一直在尝试调试这个问题,但似乎无法弄清楚。

调试时我可以看到所有变量都在它们应该在的位置,但我似乎无法将它们取出来。

运行时我收到错误消息 'dict' object is not callable

这是来自 Django 的完整错误信息

Environment: 
 
 
Request Method: GET 
Request URL: http://127.0.0.1:8000/?form_base_currency=7&form_counter_currency=14&form_base_amount=127 
 
Django Version: 1.8.6 
Python Version: 3.4.3 
Installed Applications: 
['django.contrib.admin', 
 'django.contrib.auth', 
 'django.contrib.contenttypes', 
 'django.contrib.sessions', 
 'django.contrib.messages', 
 'django.contrib.staticfiles', 
 'client'] 
Installed Middleware: 
['django.middleware.security.SecurityMiddleware', 
 'django.contrib.sessions.middleware.SessionMiddleware', 
 'django.middleware.common.CommonMiddleware', 
 'django.middleware.csrf.CsrfViewMiddleware', 
 'django.contrib.auth.middleware.AuthenticationMiddleware', 
 'django.contrib.messages.middleware.MessageMiddleware', 
 'django.middleware.clickjacking.XFrameOptionsMiddleware'] 
 
 
Traceback: 
File "/home/johan/sdp/currency-converter/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "/home/johan/sdp/currency-converter/currency_converter/client/views.py" in index 
  22.             form_base_currency = form.cleaned_data('form_base_currency').currency_code 
 
Exception Type: TypeError at / 
Exception Value: 'dict' object is not callable 

为清楚起见,我添加了调试器变量的屏幕截图。

这是我一直在使用的代码:

if request.method == 'GET': 
    form = CurrencyConverterForm(request.GET) 
    if form.is_valid(): 
        form_base_currency = form.cleaned_data('form_base_currency').currency_code 
        form_counter_currency = form.cleaned_data('form_counter_currency') 
        form_base_amount = form.data.cleaned_data('form_base_amount') 

为了让 form_base_currency 正常工作,我尝试了这些不同的方法:

form_base_currency = form.cleaned_data('form_base_currency').currency_code 
form_base_currency = form.cleaned_data.form_base_currency.currency_code 
form_base_currency = form.cleaned_data('form_base_currency.currency_code') 

它们都不起作用。谁能告诉我如何解决这个问题?

请您参考如下方法:

字典需要方括号

 form_counter_currency = form.cleaned_data['form_counter_currency'] 

尽管您可能想使用 get 以便提供默认值

 form_counter_currency = form.cleaned_data.get('form_counter_currency', None)