Reputation: 793
The Flask-Admin form tutorial code creates a list from the files in a directory. This is the populating of the list:
def build_sample_db():
# Populating the pdf files
db.drop_all()
db.create_all()
for i in [1, 2, 3]:
file = File()
file.name = "Example " + str(i)
file.path = "example_" + str(i) + ".pdf"
db.session.add(file)
db.session.commit()
return
if __name__ == '__main__':
# Build a sample db on the fly, if one does not exist yet.
build_sample_db()
# Start app
app.run(debug=True)
I've changed the code for populating to this:
# get all files in a directory
def build_sample_db():
db.drop_all()
db.create_all()
# It lists the files in a directory
ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
for f in ls_output:
file = File()
file.path = f
db.session.add(file)
db.session.commit()
return
It lists the whole directory without hard-coded values. But it refreshes only on the start of the app.
Forms in Flask-Admin is the example and how it looks.
The view is added here:
admin.add_view(FileView(File, db.session))
Files view:
class FileView(sqla.ModelView):
# Pass additional parameters to 'path' to FileUploadField constructor
form_args = {
'path': {
'label': 'File',
'base_path': file_path,
'allow_overwrite': False
}
}
# No
def __init__():
db.drop_all()
db.create_all()
ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
for f in ls_output:
file = File()
file.path = f
db.session.add(file)
db.session.commit()
Where to add the code for populating, so it can be refreshed and the files in the dir taken again? Database would be recreated as well just for the example. I don't want to create a new view, but to refresh this.
Upvotes: 0
Views: 941
Reputation: 793
Flask-Admin file example also answers the question. The files refresh, only the database is not added, but that's OK:
from flask_admin.contrib import fileadmin
# irrelevant code removed - see in the link
if __name__ == '__main__':
# Create directory
path = op.join(op.dirname(__file__), 'files')
try:
os.mkdir(path)
except OSError:
pass
# Create admin interface
admin = admin.Admin(app, 'Example: Files')
# Another way to add view
admin.add_view(fileadmin.FileAdmin(path, '/files/', name='Files'))
# Start app
app.run(debug=True)
Upvotes: 0
Reputation: 8046
Override your view's index_view
method. Something like (untested) :
from flask_admin import expose
class FileView(sqla.ModelView):
# Pass additional parameters to 'path' to FileUploadField constructor
form_args = {
'path': {
'label': 'File',
'base_path': file_path,
'allow_overwrite': False
}
}
@expose('/')
def index_view(self):
db.drop_all()
db.create_all()
ls_output = next(os.walk('/home/bor/flask-admin/examples/forms/files/'))[2]
for f in ls_output:
file = File()
file.path = f
db.session.add(file)
db.session.commit()
return super(FileView, self).index_view()
Upvotes: 1