我正在尝试创建一个简单的函数来接收从上一个视图传递来的请求数据。我想像示例(注释代码)一样使用数据创建条件。好吧,我创造:
def get_request(field_name):
data = request.GET.get('%s'%(field_name), False)
return data
在我的 views.py 中,我使用:
from .helper import get_request
def search_simple(request):
#brand=data from previous view
get_request(brand) #this raises an exception
request.GET.get('brand', False) #it work good
# and them i wont using somethin like this
#if get_request(brand):
# do something
return render(request, 'search/search_results_brand.html')
这引发了以下异常:
local variable 'brand' referenced before assignment
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/wyniki-wyszukiwania/?brand=2&model=&province=&type_car=&transmission=&price_st=&price_end=&year_production_st=&year_production_end=&car_mileage=60do100&fuel_type=BenzynaLPG&engine_power=120-150&condition=Uszkodzony&automatic_air_conditioning=on&speed_limit=on&parking_heating=on&light_xenon=on&automatic_air_conditioning=on&speed_limit=on&parking_heating=on&light_xenon=on&search=
Django Version: 2.2.4
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'app',
'app_profile',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.facebook',
'crispy_forms',
'django_select2',
'widget_tweaks']
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 "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\tymot\Desktop\car-app\app_rama\app\views.py" in search_simple
36. get_request(brand)
Exception Type: UnboundLocalError at /wyniki-wyszukiwania/
Exception Value: local variable 'brand' referenced before assignment
如何使用我的功能正确获得品牌。品牌并不总是传承下去。任何帮助将不胜感激。
答案 0 :(得分:1)
问题在于Python认为您应该在传递字符串时将变量传递给函数。尝试将get_request(brand)
替换为get_request('brand')
。