Python 如何简单地用web2py上传图像?

Python 如何简单地用web2py上传图像?,python,web2py,Python,Web2py,我所需要的只是一张图片上传到uploads文件夹,比如web2py book。 这是否仅适用于SQLForm?或者我的代码有什么问题,这是我的代码 型号:db.py db.define_table('image', Field('title'), Field('file', 'upload'), format = '%(title)s') 在mysql中,创建了一个名为varchar(70)的图像表,文件名为mediumblob 控制器 def index():

我所需要的只是一张图片上传到uploads文件夹,比如web2py book。 这是否仅适用于SQLForm?或者我的代码有什么问题,这是我的代码

型号:db.py

db.define_table('image',
    Field('title'),
    Field('file', 'upload'),
    format = '%(title)s')
在mysql中,创建了一个名为varchar(70)的图像表,文件名为mediumblob

控制器

def index():
    image_form = FORM(
    INPUT(_name='image_title',_type='text'),
    INPUT(_name='image_file',_class='upload',_type='file')
    )
    return locals()
查看

{{extend "layout.html"}}
{{=form}}

我相信
FORM
可以做
SQLFORM
所能做的一切,除非它需要更多的努力<代码>表单只是创建一个普通的html表单元素
SQLFORM
这样做,并在表单上构建所有控件,并连接提交按钮

如果可以,我总是尝试使用
SQLFORM

您的代码应该显示一个表单,但它不会将任何内容保存到数据库中。这是因为缺少关键的
表单.process
命令。正是这个命令完成了验证表单和添加或更新记录的所有艰苦工作

来自,并根据您的代码进行修改

def index():
   record = db.image(request.args(0))  # Tries to get  an existing record where the id is specified in the first argument if the url.
   image_form = SQLFORM(db.image, record)  # Creates a form based on the 'image' table. If a record was found, it will show the record details 
   if image_form.process().accepted:  # When the form is submitted (not when it is created) it will try and process it and add the record or save any changes to the record.
       response.flash = 'form accepted' 
   elif image_form.errors:
       response.flash = 'form has errors'
   return dict(form=image_form)

另一个问题是,您在控制器中调用了窗体
image\u form
,但您试图在视图中显示
form
。我上面的代码应该与您的视图配合得很好-您可以看到在返回命令(
form=image\u form
)中将
image\u form
更改为
form

我相信
form
可以完成
SQLFORM
所能做的一切,但它需要更多的努力<代码>表单只是创建一个普通的html表单元素
SQLFORM
这样做,并在表单上构建所有控件,并连接提交按钮

如果可以,我总是尝试使用
SQLFORM

您的代码应该显示一个表单,但它不会将任何内容保存到数据库中。这是因为缺少关键的
表单.process
命令。正是这个命令完成了验证表单和添加或更新记录的所有艰苦工作

来自,并根据您的代码进行修改

def index():
   record = db.image(request.args(0))  # Tries to get  an existing record where the id is specified in the first argument if the url.
   image_form = SQLFORM(db.image, record)  # Creates a form based on the 'image' table. If a record was found, it will show the record details 
   if image_form.process().accepted:  # When the form is submitted (not when it is created) it will try and process it and add the record or save any changes to the record.
       response.flash = 'form accepted' 
   elif image_form.errors:
       response.flash = 'form has errors'
   return dict(form=image_form)
另一个问题是,您在控制器中调用了窗体
image\u form
,但您试图在视图中显示
form
。我上面的代码应该可以与您的视图配合使用-您可以看到在返回命令中(
form=image\u form
)将
image\u form
更改为
form