我的问题是,当我选择datefrom和date显示错误时。“键'性别'未找到
现在即使我使用的Q对象仍然和以前一样问题。
search_gender = request.POST["gender"]
age_from = request.POST["age_from"]
age_to = request.POST["age_to"]
date_from = request.POST["date_from"]
date_to = request.POST["date_to"]
if date_from:
date_from = datetime.strptime(request.POST["date_from"],"%d %B %Y")
if date_to:
date_to = datetime.strptime(request.POST["date_to"],"%d %B %Y")
patient = PatientInfo()
p_male = 0
p_female = 0
age1 = 0
age2 = 0
date1 = 0
date2 = 0
if search_gender == 'male' :
p_male = 1
if search_gender == 'female' :
p_female = 1
if age_from:
age1 = 1
if age_to:
age2 = 1
if date_from:
date1 = 1
if date_to:
date2 = 1
if date1 and date2:
patient = PatientInfo.objects.filter(
Q(dateedit__range = (date_from,date_to))
)
当我选择date_from和date_to时,仍显示错误???甚至我没有选择男性或女性,即使我使用if.POST.has_key('gender')仍然错误 我是django的新手..请事先提前帮助... ...
答案 0 :(得分:0)
当尝试对该字典中不存在的键进行字典查找时,会引发您报告的错误 - 几乎就是错误告诉您的错误。
由于我要继续发布的是您发布的代码,我的猜测是无论出于什么原因,“gender”实际上并不存在于request.POST字典中。你需要找出原因。
通常,在处理字典时,最佳做法是首先检查密钥是否存在,或使用dict.get
方法提供后备:
# Check for dictionary key
if request.POST.has_key('gender'):
gender = request.POST['gender']
# or Provide fallback
gender = request.POST.get('gender', 'male') # if gender isn't present, 'male' will be returned
答案 1 :(得分:0)
为此,表格非常有用!
类似的东西:
forms.py
from django import forms
class MyForm(forms.Form):
GENDERS = (
('m','Male'),
('f', 'Female')
)
gender = forms.CharField(choices=GENDERS, required=False)
age_from = forms.IntegerField()
age_to = forms.IntegerField()
date_from = request.POST["date_from"]
date_to = forms.DateTimeField()
def clean_gender(self):
gender = self.cleanded_data.get('gender', 'm')
#do something with gender
return gender#now it has always a value
views.py:
def myform(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
gender = form.cleaned_data.get('gender')
#do something with data...
else:
form = MyForm()
return render_to_response('template.html', {'form':from})