请帮助修复代码。
我有一张表格:
<form class="left filter" action="/userprofile/friends_search/" method="GET">
<div class="cell">
<label class="label lbl_name" for="fld_name">Имя</label>
<input class="fld_name" type="text" name="fld_name" id="fld_name" value="">
</div>
<div class="cell">
<label class="label lbl_birth_date" for="fld_birth_date">Дата рождения</label>
<input class="fld_birth_date datepicker hasDatepicker" type="text" name="fld_birth_date" id="fld_birth_date" value="">
</div>
<div class="cell">
<input class="submit btn btn-default btn-block" type="submit" name="fld_submit" id="fld_submit" value="Найти">
</div>
</form>
发送时通过以下网址:
http://127.0.0.1:8000/userprofile/friends_search/?csrfmiddlewaretoken=aRivIk9zMHSEKLFfWc5sTerJqlvpiX96&fld_name=&fld_birth_date=
问题是控制器无法检查参数search_result是否为空值:
@login_required
def friends_search(request):
search_result = None
if request.method == 'GET' and not request.GET.get('fld_name'):
search_result = 'empty'
else:
search_result = 'full'
with open(os.path.join(settings.BASE_DIR, "search_result.txt"), "wb") as f:
f.write(bytes(search_result, 'UTF-8'))
t = loader.get_template('friends_search.html')
c = RequestContext(request, {
'search_result': search_result,
}, [custom_proc])
return HttpResponse(t.render(c))
导致调试文件search_result.txt被写入&#34; full&#34;。但是应该&#34;空&#34;
答案 0 :(得分:0)
首先,分别打印出这两个条件,例如
print request.method, request.method == 'GET', not request.GET.get('fld_name')
看看哪一个失败了。
如果 request.method不是GET 而不是调试为什么不是,如果是GET 那么试试这个:
request.method.lower() == 'get'
如果第二个失败(不应该),那么试试这个:
request.GET.get('fld_name') != ''
#但这会留下无法处理
答案 1 :(得分:0)
@login_required
def friends_search(request):
search_result = None
if request.method == 'POST':
if request.POST.get('fld_name'):
try:
fld_name = request.POST.get('fld_name')
search_result = UserProfile.objects.filter(Q(nickname__icontains=fld_name))
if not search_result:
search_result = 'По вашему запросу ничего не найдено.'
except Exception as exc:
search_result = 'В данный момент доступ к базе данных невозможен. Попробуйте повторить ваш запрос позже.'
if isinstance(search_result, str):
search_result_type = 'str'
elif isinstance(search_result, dict):
search_result_type = 'dict'
else:
search_result_type ='none'
t = loader.get_template('friends_search.html')
c = RequestContext(request, {
'CHOICES_gender': UserProfile.get_CHOICES_gender(),
'CHOICES_status': UserProfile.get_CHOICES_status(),
'city_list': UserProfile.get_city_list(),
'search_result': search_result,
'search_result_type': search_result_type,
}, [custom_proc])
return HttpResponse(t.render(c))