考虑一下我是web2py的新手。
我在控制器中使用此功能来搜索公司的条目。目标是在数据库中搜索表单中的三个参数,但我希望函数也能通过GET接受参数:
@auth.requires_login()
def index():
from datetime import datetime
data['subtitle'] = 'My Screen'
form = SQLFORM.factory(
Field('company',
type="reference company",
label='Company',
widget=SQLFORM.widgets.options.widget,
requires=IS_IN_DB(mongodb, mongodb.company.id, '%(name)s')
),
Field('initial_date',
label='Initial Date',
type="date",
requires=IS_NULL_OR(IS_DATE(format='%d/%m/%Y'))
),
Field('final_date',
label='Final Date',
type="date",
requires=IS_NULL_OR(IS_DATE(format='%d/%m/%Y'))
)
)
if str(request.env.request_method) == 'POST':
print request.post_vars
if form.accepts(request.post_vars, keepvalues = True):
params = {}
if form.vars.company is not None:
params['company'] = form.vars.company
if form.vars.initial_date is not None:
params['initial_date'] = form.vars.initial_date
if form.vars.final_date is not None:
params['final_date'] = form.vars.final_date
print 'Params: '
print params
redirect(URL('index', vars=params))
else:
for f in form.errors:
print f + ': ' + form.errors[f]
lista = {}
else:
query = None
if request.get_vars.company is not None:
query = mongodb.entry.company == request.get_vars.company
if request.get_vars.initial_date is not None:
query &= mongodb.entry.date >= datetime.strptime(request.get_vars.initial_date, '%Y-%m-%d')
if request.get_vars.final_date is not None:
query &= mongodb.entry.date <= datetime.strptime(request.get_vars.final_date, '%Y-%m-%d')
print 'Query: '
print query
if query is not None:
list = mongodb(query).select()
else:
list = {}
data['form'] = form
data['list'] = list
return dict(data=data)
只有在我提供公司的情况下才能完美运作。如果我在日期之间进行搜索,则即使日期在数据库中匹配,也不会显示任何结果。
Web2py缺乏好的例子。有人可以帮忙吗?
答案 0 :(得分:1)
不是使用POST表单然后使用GET请求重定向到相同的操作,为什么不通过GET提交表单开始:
form = SQLFORM.factory(..., _method='get')
关于您的查询,当query &=
以query
开头时,None
将无效。