【问题标题】:web2py, Two tables in one form, with image uploadweb2py,一种形式的两个表,带有图像上传
【发布时间】:2014-01-14 21:56:28
【问题描述】:

我对一种形式的两个表有疑问。我使用书中的示例作为参考,但我在表单中插入图像,它确实上传了文件,但 URL(图像名称)全错了,我不知道如何让它把正确的 url 设置为图片名称。

这是我的代码:

db.define_table('forum',
                Field('title','string', unique=True, label=T('Title')),
                Field('body','text', requires=IS_NOT_EMPTY(),label=T('Body')),
                Field('posted_on','datetime',readable=False, writable=False),
                Field('posted_by','reference auth_user',readable=False, writable=False),
                Field('category',db.category))

db.define_table('doc',
                Field('forum_id', 'reference forum',readable=False, writable=False),
                Field('image','upload',uploadfolder=os.path.join(request.folder,'uploads'), autodelete=True),
                Field('posted_on', 'datetime',default=request.now, readable=False, writable=False),
                Field('posted_by','reference auth_user', readable=False, writable=False))


def post():
    form=SQLFORM.factory(db.forum,db.doc)
    db.forum.posted_on.default =request.now
    db.forum.posted_by.default = auth.user
    db.doc.posted_on.default = request.now
    db.doc.posted_by.default= auth.user

    if form.process().accepted:
        id = db.forum.insert(**db.forum._filter_fields(form.vars))
        form.vars.forum_id=id
        id = db.doc.insert(**db.doc._filter_fields(form.vars))
        session.flash='Form Posted'
        redirect(URL('community'))
        redirect
    return dict(form=form)

【问题讨论】:

    标签: web2py


    【解决方案1】:

    SQLFORM.factory() 创建一个带有虚拟表的虚拟 DAL 实例(默认命名为“no_table”)。上传字段在存储文件时使用DAL 表的名称作为新文件名的一部分。文件名应以“doc.”开头,而是以“no_table.”开头。一种解决方法是指定由SQLFORM.factory() 创建的虚拟表的名称:

    SQLFORM.factory(db.forum, db.doc, table_name='doc')
    

    如果两个表都包含上传字段,显然这将不起作用,因此在这种情况下您需要更复杂的解决方法(这将涉及在调用 form.process() 之前直接从 request.vars 提取上传的文件 - 他们可以使用db.doc.image.store() 方法重命名/存储)。

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 2018-12-30
      相关资源
      最近更新 更多