Project was moved into its own organization: https://github.com/flask-admin
Please update your references.
Simple and extensible administrative interface framework for Flask
License: Other
Project was moved into its own organization: https://github.com/flask-admin
Please update your references.
I have a question on how to implement a computed field.
For example, I'd like to add such a field to column_list, smth like that:
class UserProfile(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode(128))
admin = db.Column(db.Boolean, index=True)
def get_name_ex(self):
return '%s (admin: %s)' % (self.name, self.admin)
...
class UserProfileAdmin(ModelView, AuthBaseView):
column_list = ['get_name_ex']
But this does not work as expected.
Please advise.
contrib.peewee fails importing PrimaryKeyField, it has been changed to AutoField.
can't find admin/master.html'
To reproduce, go here: http://examples.flask-admin.org/geo/admin/multipoint/edit/?url=%2Fgeo%2Fadmin%2Fmultipoint%2F&id=1
and click the "edit layers" icon (above the delete trashcan).
Uncaught TypeError: Cannot set property 'previousOptions' of undefined
Is this an issue with Leaflet, or something wrong with the flask-admin implementation?
Hello, im using Flask-Admin==1.3.0.
I', displaying data from different datasources:
admin.add_view(MyModelView(Token, session=Session()))
admin.add_view(MyModelView(LoginAttempt, session=Session()))
admin.add_view(MyModelView(Device, session=Session()))
admin.add_view(MyModelView(DeviceInfo, session=Session()))
admin.add_view(MyModelView(HCUser, session=Session()))
admin.add_view(MyModelView(Config, session=Session()))
admin.add_view(MyModelView(Report, session=CouponSession()))
admin.add_view(MyModelView(File, session=CouponSession()))
admin.add_view((MyModelView(User, db.session)))
admin.add_view((MyModelView(Role, db.session)))
And i wonder why some data, like token or device appears in admin panel with big latency.
Is it problem of SQLAlchemy session or something else?
Flask Admin use get_url instead of url_for in jinja template. Flask-S3 override url_for in jinja template to use static file on S3.
Could you provide a way to get admin static files loading from external url?
Hello folks,
I have encountered this error and spent hours on looking for a fix. I'm using the bootstrap3 examples and eventually run to this problem. Luckily this site has a fix for it:
https://www.bountysource.com/issues/7953344-nonetype-object-has-no-attribute-resolve
<div class="row">
<div class="col-lg-12">
{{ layout.messages() }}
{% set render_ctx = h.resolve_ctx() %}
{% block body %}{% endblock %}
</div>
</div>
moved to flask-admin github
Hello,
I'm helping someone learn to use Vue.js and Flask together, and since both Vue.js and Flask use the {{ }} syntax, I've set Flask to use %% %% instead. Now this person I'm helping is trying to set up Flask Admin and is getting errors, apparently because of the change to Flask's delimiters.
Is there any way to set Flask Admin to use different delimiters?
Hi, I've been lookinh for in the documentation and examples but I couldn't find it yet.
There is a way to use dropdown menu or multilevel menu?
For example I have my View Users and another called Roles, I want they both be inside of a parent link called User Management, and by clicking this link it show my two views links.
Thanks a lot (excuse my bad english)
I need to have dynamic filter options in my admin setup, but I can't do it, even if options is callable it's being evaluated in parse time. Maybe I'm missing something, but could not find in docs how to setup options dynamically.
I'm using mongoengine and just tried flask-admin.
I declared a field as LongField
and that just didn't seem to show in the interface when I tried to edit and create a model.
My EmbeddedDocumentFields also don't show up in the interface. But EmbeddedFields and ListFields work.
The unique validator causes problems when used with Postgres types such as MACADDR. Select on a table with an invalid MAC Address will cause an error and I see no easy way to force MAC Address validation to run before the unique validator. Is there a way to disable the unique validator? The only workaround I currently see is to avoid using 'unique=True' in the model altogether.
# Create primary key map
pk_map = dict((str(getattr(v, self._pk)), v) for v in values)
# Handle request data
for field in self.entries:
field_id = field.get_pk()
is_created = field_id not in pk_map
You can see from the code, the key in pk_map is converted to str, but the field_id is not, it could be an integer, so the field_id not in pk_map
could be incorrect.
This is not an issue this is more like a question, i'm working with file admin and i want to add an column_extra_row_actions, i have tried that using the following code:
class MyView(FileAdmin):
can_upload = False
can_delete = True
can_mkdir = False
column_extra_row_actions = [
EndpointLinkRowAction('glyphicon glyphicon-play','')
]
file_admin_view = MyView('/home/pi/Desktop/projects/', url = '/' , name='Projects')
admin = Admin(app,
name='projects',
index_view = file_admin_view,
template_mode='bootstrap3')
but i haven't had success.
do you know what am i doing wrong?
what's is the correct way to do this?, i have fallowed the documentation and i have found this:
from flask_admin.model.template import EndpointLinkRowAction, LinkRowAction
class MyModelView(BaseModelView):
column_extra_row_actions = [
LinkRowAction('glyphicon glyphicon-off', 'http://direct.link/?id={row_
˓→id}'),
EndpointLinkRowAction('glyphicon glyphicon-test', 'my_view.index_view
˓→')
]
but i don't know if this methodology also works with fileadmin view. What i understand is that BaseModelView is for database model view modification, but i'm not sure if it also works with fileadmin view.
Thanks
Hi,
I am absolutely beginner in Flask-Admin.
When I try examples, i got exception:
jinja2.exceptions.TemplateNotFound: admin/master.html.
As jinja doesn't see master template in site-packages/flask_admin/templates???
Any hint, please?
A change in SQLAlchemy 1.1.0 broke postgres ARRAY fields (I don't know about other databases).
Using Flask-Admin 1.4.2 and SQLAlchemy 1.1.0 results into the ARRAY field not showing in the edit form. Downgrading to SQLAlchemy 1.0.0 resolves the issue for me.
I will submit a pull request if I find a solution.
See:
http://docs.sqlalchemy.org/en/latest/changelog/changelog_11.html#change-1.1.0b2-postgresql
I implemented secure views for SQLAlchemy models using the example. But when I'm adding file admin, it shows up before login. Is there any way to secure the file admin?
Is is possible to register callback that wil update field X of model when field Y is updated in admin panel?
All instances of 'current_user.is_authenticated()' in the python code and html files in the auth example need to be updated to 'current_user.is_authenticated' to match the recent changes in Flask-Login.
This function, as well as a few other functions for the User model, were changed to properties.
Hi,
I'm using a flask-admin app as the DB frontend for https://github.com/ROBelgium/MSNoise, and I provide a way to dynamically add Views for "modules" or "plugins", i.e. packages, via entry_points.
My way of doing works very nicely for classic flask-admin views (list/edit), but if the plugin requires a custom template, I didn't find a way to pass the location of the template file.
In the MSNoise admin loading part:
if plugins:
plugins = plugins.split(',')
for ep in pkg_resources.iter_entry_points(group='msnoise.plugins.admin_view'):
module_name = ep.module_name.split(".")[0]
if module_name in plugins:
admin.add_view(ep.load()(db))
and the structure of the plugin is;
│ setup.py
│ __init__.py
├───msnoise_qc
│ │ compute.py
│ │ default.py
│ │ install.py
│ │ plugin_definition.py
│ │ table_def.py
│ │ __init__.py
│ │
│ └───templates
│ └───admin
│ data_qc.html
and the declaration is:
class QCView(BaseView):
view_title = "MSNoise QC"
def __init__(self, session, **kwargs):
# You can pass name and other parameters if you want to
super(QCView, self).__init__(name="QC", category="Database", **kwargs)
@expose('/')
def index(self):
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'templates')
return self.render(template='data_qc.html', tmpl_dir=tmpl_dir)
Here I tried setting tmpl_dir
which doesn't seem to have an effect... Is there a way to do this properly? Overriding the jinja2 loader ?
Best regards,
I've a Task model and User model
and I added task model to the UserModelView in inline_models, and I get the expected behavior with list of tasks and add task button that creates a simple form. Problem is I want for that specific part to use the modal dialog for more fields.
Hi,
Do we know if Admin supports customising the fields of a model in form_ajax_refs?
I've opened a stackoverflow question regarding what I'm after specifically: https://stackoverflow.com/questions/31139948/flask-admin-custom-queryajaxmodelloader
Thanks!
Please take a look at WTForms issue wtforms/wtforms#261, it may be related to the Flask-Admin implementation of the gettext
Hi,
Thanks for Flask-admin, it is really awesome ! I have managed to do everything that I wanted with it so far but I am stumbling on a problem now :)
I have a model Purchase
that has to recalculate the total_price
of the Purchase
when you save it.
Using peewee models :
class Purchase(BaseModel):
quantity = IntegerField()
product = ForeignKeyField(Product)
total_price = IntegerField()
@pre_save(sender=Purchase)
def pre_save_purchase(model_class, instance):
if not created:
instance.total_price = instance.quantity * instance.product.price
The problem is: when I inline edit the quantity
, I do not see the change to the total_price
.
I have looked a bit at the code to find a work around. My idea would be to override the ajax_update
route and send back the HTML code to replace in the cells. I would have then to add a success
callback to the x-editable widget that would replace the data in the row with the data sent back by the server.
So far I have:
In the view:
@expose('/ajax/update/', methods=('POST',))
def ajax_update(self):
"""
Edits a single column of a record in list view.
"""
response = make_response(super(UserView, self).ajax_update())
# do nothing if the update was not successful
if response.status_code != 200:
return response
form = self.list_form()
for field in form:
# only the submitted field has a positive last_index
if getattr(field, 'last_index', 0):
record = self.get_one(str(field.last_index))
t = Template(self.edit_template)
ctx = t.new_context()
get_value = lambda row, c: self.get_list_value(ctx, row, c)
get_pk_value = lambda row: self.get_pk_value(row)
cells = {}
# replicate the list template logic
for c, name in self._list_columns:
if '.' in c:
continue
if self.is_editable(c):
if getattr(form, 'csrf_token', None):
cell = form[c](pk=get_pk_value(record), value=get_value(ctx, record, c), csrf=form.csrf_token._value())
else:
cell = form[c](pk=get_pk_value(record), value=get_value(record, c))
else:
cell = get_value(record, c)
cells[c] = cell
return jsonify({'cells': cells})
In the template:
{% block tail %}
{{ super() }}
<script type='text/javascript'>
// customize fa-form
var form = window.faForm;
var onSuccessXEditable = function (data) {
var $this = $(this);
var cells = data.cells;
var tr = $this.parents('tr')
for (name in cells) {
if (cells.hasOwnProperty(name)) {
var td = tr.find('.col-' + name);
var html = cells[name];
td.html(html);
}
}
form.applyGlobalStyles(tr);
};
$.extend($.fn.editable.defaults, {
success: onSuccessXEditable
});
</script>
{% endblock %}
It seems to work OK apart for the fields that have a dot in them, I could not get get_list_value
on those.
I think it would be cool if this functionality was in Flask-admin
. I would be ready to do a pull request if my approach seems reasonable. What do you think ?
Hello !!
I'm using flask_admin version 1.3.0 on windows, with flaskalchemy and SQLServer, and I get the first page of the views right, but when I try to go to any other I get this error:
sqlalchemy.exc.CompileError
CompileError: MSSQL requires an order_by when using an OFFSET or a non-simple LIMIT clause
Thanks a lot for this awesome tool!!
Use the sqlalchemy example:
start = composite(Point, x1, y1)
This will reproduce the warning
flask_admin/contrib/sqla/view.py:426: UserWarning: Can not convert multiple-column properties
Following this example I integrated Flask admin with some already created peewee models. Everything looks great until I try the list view of the admin interface, but first some context:
The important part of the app.py file:
@inject.params(db=Database)
def create_app(config_object=DevConfig, db=None):
app = Flask(__name__)
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_errorhandlers(app)
return app
def register_extensions(app):
"""Register Flask extensions."""
assets.init_app(app)
bcrypt.init_app(app)
cache.init_app(app)
login_manager.init_app(app)
debug_toolbar.init_app(app)
admin = Admin(app, name=__name__, template_mode='bootstrap3')
__add_admin_views(admin)
return None
def __add_admin_views(admin):
admin.add_view(ClientAdmin(entities.Client))
return None
This happens when I try to request the list of clients (http://127.0.0.1:5000/admin/client/):
Traceback (most recent call last):
File "MY_ENV_PATH/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "MY_ENV_PATH/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "MY_ENV_PATH/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "MY_ENV_PATH/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "MY_ENV_PATH/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "MY_ENV_PATH/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "MY_ENV_PATH/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "MY_ENV_PATH/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/base.py", line 68, in inner
return self._run_view(f, *args, **kwargs)
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/base.py", line 367, in _run_view
return fn(self, *args, **kwargs)
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/model/base.py", line 1738, in index_view
view_args.search, view_args.filters)
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/contrib/peewee/view.py", line 353, in get_list
query = self.get_query()
File "MY_ENV_PATH/lib/python2.7/site-packages/flask_admin/contrib/peewee/view.py", line 328, in get_query
return self.model.select()
File "MY_ENV_PATH/lib/python2.7/site-packages/peewee.py", line 4458, in select
query = SelectQuery(cls, *selection)
File "MY_ENV_PATH/lib/python2.7/site-packages/peewee.py", line 2696, in __init__
self.require_commit = self.database.commit_select
AttributeError: 'function' object has no attribute 'commit_select'
As seen in SO
I have a working example here: https://github.com/citizen-stig/flask_admin_enum
I investigated it a little bit and maybe problem is in SQLalchemy and how it provides information about Enum column.
I want my login and register pages to have the same layout as the admin pages, but I always get the infamous errors showing that 'admin_base_template' is undefined.
How can I accomplish this (DRY)?
I want to add divider
<li class="divider"></li>
in the generated admin menu. I've investigated the code a bit, but still have no idea how to do that. It can be small but useful feature.
Thanks!
I'm using mongoengine and I have some issues when using Flask Admin.
If I have a Embedded document or ReferenceObject, the admin just shows EMail object
or User object
or <class_name> object
in general. Seems as though these are just being converted to strings - which is not a very correct way to do this.
When I try to create a model which has a Reference field, I get a drop down with every element as User Object
- which is very confusing as I have no idea what their id is !
For displaying I suggest you use links with the Object id or something.
*.is_authenticated()
throwing:
File "/tmp/flask-admin/examples/auth/app.py", line 105, in index
if not login.current_user.is_authenticated():
TypeError: 'bool' object is not callable
Fix:
Change all is_authenticated() to is_authenticated (in all *.py and *.html)
€dit: Tested with python2.7, 3.4 and 3.5
I am making a multi-tenant application that includes an Admin side for each tenant.
I added the subdomain
config in the Admin initialization to capture the dynamic subdomain and added the parameter to each exposed route, like so:
class CustomAdminIndexView(AdminIndexView):
@expose('/')
def index(self, subdomain):
return super(CustomAdminIndexView, self).index()
...
admin = Admin(app, name='Admin Panel', base_template='layout.html', index_view = CustomAdminIndexView(), template_mode='bootstrap3', subdomain='<subdomain>')
The problem is that at render time, in the templates (and likely elsewhere, too) where there are calls to url_for
for static files (the admin.static
endpoint), it fails because it is now expecting the subdomain parameter. The immediate Error I am getting is from a url_for
in /usr/local/lib/python2.7/dist-packages/flask_admin/templates/bootstrap3/admin/static.html
:
BuildError: Could not build url for endpoint 'admin.static' with values ['filename', 'v']. Did you forget to specify values ['subdomain']?
I assume there is a way to override the file mentioned (though not sure how), but I also assume that is probably not the only place where this would need to be fixed.
How could I handle this so for anywhere where it may happen?
Hello folks; just had a problem here where I have to set my admin index_view after instantiating my extension in order to avoid a circular import. This happened because of the way I have my extensions organized. Anyone had the same issue?
First of all I like to show you my test project skeleton:
app.py
app/
|--mysite/
|--------__init__.py
|--------models.py
|--------views.py
|--------templates/
|-----------------index.html
|--admin/
|--------__init__.py
|--------models.py
|--------views.py
|--------templates/
|-----------------editor.html
In app.py, the codes are like below:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
Now, please let me make something clear. In mysite folder I'll make a flask blueprint, which has a template file index.php in templates folder. After that, I'll try to make an admin folder to initialize flask-admin admin object. This folder also has a templates folder. I like to override flask-admin base templates with the editor.html template in regarding templates
folder. When I try, the flask-admin admin object only check in the blueprint templates folder. But I need different templates folder for mysite
and admin
. Any example for this, please?
is_authenticated is now a bool not a method.
Would you mind if I tried to add support for a Foundation 5 admin template? I read in the documentation it should be suggested (PR) as a contrib module? Is that ok? I really love your project and always work with Foundation, so I wanted to give it a try.
Url with http works fine on http pages However the url is not working on https pages.
On this line
https://github.com/mrjoes/flask-admin/blob/master/flask_admin/model/base.py#L1121
the is_created param is not passed, causing TypeError
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.