Python 将默认值设置为view web2py中的表字段
我的应用程序有以下代码:Python 将默认值设置为view web2py中的表字段,python,web2py,Python,Web2py,我的应用程序有以下代码: db.define_table('event', Field('name'), Field('date','date'), Field('location'), format='%(name)s') db.define_table('presentations', Field('event', db.event), Field('title'), Field('description'), Field('level'))
db.define_table('event',
Field('name'),
Field('date','date'),
Field('location'),
format='%(name)s')
db.define_table('presentations',
Field('event', db.event),
Field('title'),
Field('description'),
Field('level'))
db.define_table('presenters',
Field('name'),
Field('company'),
Field('resume'),
Field('avatar','upload),
format='%(name)s')
db.define_table('presentations_presenters',
Field('presentation', db.presentation),
Field('presenter', db.presenters))
然后,我为演示创建了一个控制器:
def admpresentations():
presentationList=db(db.presentations.event==request.vars.eventid).select()
return dict(presentations=presentationList)
在我看来,这表现为:
{{for presentation in presentations:}}
{{=presentation.title}}
{{=presentation.description}}
{{=presentation.level}}
{{pass}}
现在,我的问题是:我必须为每个演示添加演示者。为此,我想为演示文稿\u presenters.presentation
设置一个默认值,因为每个演示文稿可以有多个演示文稿,所以我在视图中尝试以下操作:
{{for presentation in presentations:}}
{{=presentation.title}}
{{=presentation.description}}
{{=presentation.level}}
<!--This is for setting a default value to presentation field, but doesn't work-->
{{db.presentations_presenters.presentation.default=presentation.id}}
<!--This creates the form, but default values are ignored-->
{{=crud.create(db.presentations_presenters}}
{{pass}}
设置默认值确实有效,但数据不会保存到数据库中。crud.create()
在表单中创建一个默认的\u formname
隐藏字段,该字段与\u formkey
隐藏字段一起使用,以防止CSRF攻击。您的代码最终创建了多个同名表单。因此,会话中存储的\u formkey
值将仅与创建的最后一个表单匹配,因此,由于\u formkey
不匹配,任何早期表单的提交都将被拒绝。为了避免这种情况,您必须为每个表单指定一个唯一的名称。例如:
{{=crud.create(db.presentations_presenters,
formname='presenters/%s' % presentation.id)}}
另外,如果您想改用SQLFORM
,只需调用.process()
方法在视图中对其进行处理:
{{=SQLFORM(db.presentations_presenters).process(
formname='presenters/%s' % presentation.id)}}
为什么要在视图中创建表单
简单地在控制器中创建一个SQLFORM或SQLFORM.factory,并使用form.=默认值设置默认值。我在页面中显示记录,并且对于每个记录,都有一个新的表单,用于根据curret记录和另一个表添加数据,如果我使用控制器,我只能给出一个参数,在视图中创建表单允许我为一些字段设置默认值。太棒了,这实际上很有效。。。但我必须刷新页面才能看到新记录,这可以通过next=URL()解决。。。谢谢你!
{{=SQLFORM(db.presentations_presenters).process(
formname='presenters/%s' % presentation.id)}}