您可以修改你的模型,看起來像這樣:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
url_pic = Column(String(50), nullable=False)
pic = Column(LargeBinary, nullable=False)
...
現在,你應該從flask.ext.admin.contrib.sqla
繼承ModelView
。然後,您將該子類的一個實例添加到Admin實例。以下源代碼可以幫助您明白這一點。
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.form.upload import FileUploadField
from wtforms.validators import ValidationError
from flask.ext.admin import Admin
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
import imghdr
app = Flask(__name__)
db = SQLAlchemy(app)
class UserAdminView(ModelView):
def picture_validation(form, field):
if field.data:
filename = field.data.filename
if filename[-4:] != '.jpg':
raise ValidationError('file must be .jpg')
if imghdr.what(field.data) != 'jpeg':
raise ValidationError('file must be a valid jpeg image.')
field.data = field.data.stream.read()
return True
form_columns = ['id','url_pic', 'pic']
column_labels = dict(id='ID', url_pic="Picture's URL", pic='Picture')
def pic_formatter(view, context, model, name):
return 'NULL' if len(getattr(model, name)) == 0 else 'a picture'
column_formatters = dict(pic=pic_formatter)
form_overrides = dict(pic= FileUploadField)
form_args = dict(pic=dict(validators=[picture_validation]))
admin = Admin(app)
admin.add_view(UserAdminView(User, db.session, category='Database Administration'))
...
在這裏您可以找到的文檔爲ModelView
:link here 我希望這可以幫助別人!
你如何添加用戶和上傳照片?你使用2種不同的觀點?你能分享一些代碼嗎? – codegeek
我的管理控制檯的視圖如下所示:http://pastebin.com/9J6pEA0Z。正如你可以想象的那樣,它將爲Content和FileUpload渲染一個單獨的視圖(我想要合併,這樣當我添加一個內容時,url將與上傳的文件相同)Thnks! – gpestana