Giter Club home page Giter Club logo

flask-admin's Introduction

flask-admin's People

Contributors

abkfenris avatar artemserga avatar bryhoyt avatar cereynaud avatar cosmius avatar ctoth avatar david-e avatar dmedvinsky avatar eyvoro avatar gstf avatar italomaia avatar iurisilvio avatar jacobsvante avatar jadkik avatar lanybass avatar mrjoes avatar msempere avatar pawl avatar petrus-jvrensburg avatar plaes avatar raz0r avatar samuelcolvin avatar silme-ea avatar singingwolfboy avatar sumpfgottheit avatar tahajahangir avatar techniq avatar uniphil avatar wilsaj avatar zavatskiy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-admin's Issues

Secure File admin

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?

Example "auth" is not working

*.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

pk populate in InlineModelFormList could be wrong

        # 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.

Template folder confliction between flask-admin and flask blueprint

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?

How to use Flask-S3

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?

adding custom template folder for packages (loaded via entry points)

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,

Computed field

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.

FlaskAdmin issues with EmbeddedDocuments

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.

Data appears lately in admin panel.

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?

Dropdown menu or multilevel menu

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)

Pagination on SQLServer

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!!

FlaskAdmin : mongoengine's some fields don't work

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.

getting AttributeError: 'function' object has no attribute 'commit_select' in a Flask-Admin Peewee web app

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 Code

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

The Error

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

admin.static endpoint and subdomains

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?

How can I add divider in the menu?

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!

Lazy set AdminIndexView

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?

Unique validator run before MACAddress validator

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.

Edit callback

Is is possible to register callback that wil update field X of model when field Y is updated in admin panel?

Inline editing does not reload model after saving

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 ?

Error when Flask delimiter has changed

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?

How to to use modal dialog to create a new inline model

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.

jinja2.exceptions.TemplateNotFound: admin/master.html

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?

add column_extra_row_actions in fileadmin view

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

Update auth example to match recent Flask-Login changes

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.

Foundation Template

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.