我在python django中处理表单时遇到了一些问题。处理表单时有一些不寻常的行为。下面是我的表单和在视图中处理表单的函数的一部分。我是python和django的新手,所以任何帮助都会非常感激。
class SearchForm(forms.Form):
pr_name = forms.CharField(label="Pr Name", max_length=64, required=False)
org = forms.ModelChoiceField(queryset=Org.objects.all(), required=False)
group_name = forms.CharField(label="Unique Submission Name", max_length=64, required=False)
group_ref = forms.CharField(label="Ref", max_length=12, required=False)
group_url = forms.URLField(label="URL", required=False)
def search(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
p_ids = []
g_ids = []
f_ids = []
logging.debug('hello1')
# Filter first
firstQuery = 'SELECT * FROM pr where '
pr_name = form.cleaned_data['pr_name']
if pr_name:
logging.debug('hello2')
firstQuery += '(name like \'%' + pr_name + '%\')'
else:
pass
logging.debug('hello3')
org = form.cleaned_data['org']
if org:
org = Org.objects.get(name = org)
org_id = org.id
firstQuery += '(org_id = ' + str(org_id) + ')'
else:
pass
firstQuery = firstQuery.replace(')(', ') AND (')
logging.debug('First query: %s' % firstQuery)
p_search_results = P.objects.raw(firstQuery)
logging.debug('First query: %s' % p_search_results)
for x in p_search_results:
p_ids.append(x.id)
logging.debug('p_ids: %s' % p_ids)
# Filter Group
secondQuery = 'SELECT * FROM group where '
group_name = form.cleaned_data['group_name']
if group_name:
secondQuery += '(name like \'%' + group_name + '%\')'
else:
pass
group_ref = form.cleaned_data['group_ref']
if group_ref:
secondQuery += '(ref like \'%' + group_ref + '%\')'
else:
pass
group_url = form.cleaned_data['group_url']
if group_url:
secondQuery += '(method_url like \'%' + group_url + '%\')'
else:
pass
secondQuery = secondQuery.replace(')(', ') AND (')
logging.debug('Second query: %s' % secondQuery)
group_search_results = PredictionGroup.objects.raw(secondQuery)
logging.debug('Second query: %s' % group_search_results)
for x in group_search_results:
g_ids.append(x.id)
logging.debug('g_ids: %s' % g_ids)
...
...
...
当我在表单中输入pr_name并提交时,视图进入第一个if语句在控制台中输出'hello1'和'hello2',但跳过'hello3'并跳过第二个if语句并向前跳转到{ {1}}
调试输出为:
secondQuery = secondQuery.replace(')(', ') AND (')
错误是:
DEBUG hello1
DEBUG hello2
预期产出:
UnboundLocalError at /search/
local variable 'secondQuery' referenced before assignment
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File ".../views.py" in search
209. secondQuery = secondQuery.replace(')(', ') AND (')
Exception Type: UnboundLocalError at /search/
Exception Value: local variable 'secondQuery' referenced before assignment
答案 0 :(得分:1)
可能在你的源代码中你有空格和标签混合,你认为应该执行的代码块实际上没有被执行,因为它在“if”语句中?