python - 为 View 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('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))

然后我创建了一个用于演示的 Controller :

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}}

现在,我的问题是:我必须为每个演示文稿添加演示者。为此,想要为 presentations_presenters.presentation 设置一个默认值,因为每个演示文稿可以有多个演示者,所以我在我的 View 中尝试这样做:

{{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}}

尝试使用 SQLFORM,但我不知道如何在 View 中处理它,因此数据没有写入数据库...有任何线索吗?

编辑

最后一行:

    {{=crud.create(db.presentations_presenters}}

设置默认值确实有效,但数据未保存到数据库中。

最佳答案

crud.create() 在表单中创建默认的_formname隐藏字段,该字段与_formkey隐藏字段结合使用防止 CSRF 攻击。您的代码最终会创建多个具有相同名称的表单。因此, session 中存储的 _formkey 值将仅与最后创建的表单匹配,因此任何早期表单的提交都将因 _formkey 不匹配而被拒绝。为了解决这个问题,您必须为每个表单指定一个唯一的名称。例如:

{{=crud.create(db.presentations_presenters,
               formname='presenters/%s' % presentation.id)}}

另外,如果您想使用SQLFORM,只需在 View 中调用.process()方法即可处理它:

{{=SQLFORM(db.presentations_presenters).process(
       formname='presenters/%s' % presentation.id)}}

关于python - 为 View web2py 内的表字段设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20018767/

相关文章:

python - Django 国际化 - Gettext 错误

html - 如何防止 web2py 自动编码 html 实体?

python - 如何在Windows 10上连接web2py和mysql

python - web2py:如何实现网格的多个过滤器?

web2py - 获取所有登录用户Web2py

python - 做一个好公民和网络抓取

python - 帮助我在 Python 中实现反向传播

database - 提高 web2py 性能 - 数据库和 apache

Python - 如何检查/发现列表有引用?

python - Django MPESA 与 C2B 收款机号码支付和 STK 推送的集成