customize widget for a form in modelview in flask-admin

  • Last Update :
  • Techknowledgy :

To overwrite this behavior, you can set the form_overrides field:

from wtforms.fields
import TextAreaField

class MyModelView(ModelView):
   form_overrides = dict(string = TextAreaField)
def is_accessible(self):
   return current_user.usergroup.name == 'admin'

Suggestion : 2

Dictionary of form widget rendering arguments. Use this to customize how widget is rendered without using custom template.,Flask-Admin will generate standard per-row actions (edit, delete, etc) and will append custom actions from this list right after them.,Setting this to true will enable the details view. This is recommended when there are too many columns to display in the list_view.,You can use tuple to control ascending descending order. In following example, items will be sorted in descending order:

class MyModelView(BaseModelView):
   column_list = ('name', 'last_name', 'email')
class MyModelView(BaseModelView):
   column_list = ('name', User.last_name)
class MyModelView(BaseModelView):
   column_exclude_list = ('last_name', 'email')
class MyModelView(BaseModelView):
   column_labels = dict(name = 'Name', last_name = 'Last Name')
class MyModelView(BaseModelView):
   column_descriptions = dict(
      full_name = 'First and Last name'
   )
class MyModelView(BaseModelView):
   column_formatters = dict(price = lambda v, c, m, p: m.price * 2)

Suggestion : 3

The following works fine to add my custom anycodings_python ColorField to the "edit" form, but what I anycodings_python really want is to edit it using the anycodings_python column_editable_list option.,When I add the "color" field to the anycodings_python column_editable_list I get the following anycodings_python error:,Then override the get_list_form() method anycodings_flask in your model view, to use your anycodings_flask CustomWidget.,The Flask-Admin model view class

The following works fine to add my custom anycodings_python ColorField to the "edit" form, but what I anycodings_python really want is to edit it using the anycodings_python column_editable_list option.

from flask_admin.contrib.sqla
import ModelView
from wtforms.widgets.html5
import ColorInput
from wtforms.widgets
import TextInput
from wtforms
import StringField
from wtforms.fields
import TextAreaField

from app
import db

class UnitType(db.Model):
   ""
"Create a SQLAlchemy model for the our manufactured units"
""

__tablename__ = "unit_types"

id = db.Column(INTEGER, primary_key = True)
unit = db.Column(TEXT, unique = True, nullable = False)
color = db.Column(TEXT, nullable = True)

class ColorField(TextAreaField):
   ""
"Create special ColorField for the color picker"
""

# Set the widget
for this custom field
widget = ColorInput()

class UnitModelView(ModelView):
   ""
"The Flask-Admin view for the UnitModel model class"
""

# List of columns to display in the view
column_list = (
   "unit",
   "color",
)

# List of columns that are immediately "editable"
# without clicking "edit"
first(super - nice feature)
column_editable_list = (
   "unit",
   # If I uncomment the following, I get an error...
   # "color",
)

# Specify my own custom color picker form field type
form_overrides = {
   'color': ColorField
}

# form_args = {
   # 'color': {
      # 'type': "color",
      #
   },
   #
}

# form_widget_args = {
   # 'color': {
      # 'type': "color",
      #
   },
   #
}

When I add the "color" field to the anycodings_python column_editable_list I get the following anycodings_python error:

Exception: Unsupported field type: <class 'app.admin.admin.ColorField'>

First create a custom widget so we don't anycodings_flask get the following error:

Exception: Unsupported field type: <class 'flask_admin.model.fields.AjaxSelectField'>

Here's the custom widget:

from flask_admin.contrib.sqla.ajax
import QueryAjaxModelLoader
from flask_admin.model.widgets
import XEditableWidget
from wtforms.widgets
import html_params
from flask_admin.helpers
import get_url
from flask_admin.babel
import gettext
from flask_admin._backwards
import Markup
from jinja2
import escape

class CustomWidget(XEditableWidget):
   ""
"WTForms widget that provides in-line editing for the list view"
""

def get_kwargs(self, field, kwargs):
   ""
"Return extra kwargs based on the field type"
""

if field.type == "ColorField":
   # A select2 list of pre - defined colors, formatted to display the actual color
kwargs["data-role"] = "x-editable-color"
kwargs["data-type"] = "select2"
else:
   super().get_kwargs(field, kwargs)

return kwargs

Then override the get_list_form() method anycodings_flask in your model view, to use your anycodings_flask CustomWidget.

from flask_admin.contrib.sqla
import ModelView

class MyModelView(ModelView):
   ""
"
Customized model view
for Flask - Admin page(
   for database tables)
https: //flask-admin.readthedocs.io/en/latest/introduction/#
   ""
"

# Custom templates to include custom JavaScript and override the {
   % block tail %
}
list_template = 'admin/list_custom.html'

can_create = True
can_edit = True

def get_list_form(self):
   ""
"Override this function and supply my own CustomWidget with AJAX 
for lazy - loading dropdown options ""
"

if self.form_args:
   # get only validators, other form_args can
break FieldList wrapper
validators = dict(
   (key, {
      'validators': value["validators"]
   }) for key, value in iteritems(self.form_args) if value.get("validators")
)
else:
   validators = None

# Here 's where I supply my custom widget!
return self.scaffold_list_form(validators = validators, widget = CustomWidget())

Notice the select2 I added to the anycodings_flask $el.editable( options:

...
      switch (name) {
        case "select2-ajax":
          processAjaxWidget($el, name);
          return true;

        case "x-editable":
          $el.editable({
            params: overrideXeditableParams,
            combodate: {
              // prevent minutes from showing in 5 minute increments
              minuteStep: 1,
              maxYear: 2030,
            },
          });
          return true;

        case "x-editable-color":
          // Nice pastel colors
          var colorsource = [
            {value: "#f7f7f7", text: "#f7f7f7"},
            {value: "#292b2c", text: "#292b2c"},
            {value: "#87CEEB", text: "#87CEEB"},
            {value: "#32CD32", text: "#32CD32"},
            {value: "#BA55D3", text: "#BA55D3"},
            {value: "#F08080", text: "#F08080"},
            {value: "#4682B4", text: "#4682B4"},
            {value: "#9ACD32", text: "#9ACD32"},
            {value: "#40E0D0", text: "#40E0D0"},
            {value: "#FF69B4", text: "#FF69B4"},
            {value: "#F0E68C", text: "#F0E68C"},
            {value: "#D2B48C", text: "#D2B48C"},
            {value: "#8FBC8B", text: "#8FBC8B"},
            {value: "#6495ED", text: "#6495ED"},
            {value: "#DDA0DD", text: "#DDA0DD"},
            {value: "#5F9EA0", text: "#5F9EA0"},
            {value: "#FFDAB9", text: "#FFDAB9"},
            {value: "#FFA07A", text: "#FFA07A"},
            {value: "#fce38a", text: "#fce38a"},
            {value: "#eaffd0", text: "#eaffd0"},
            {value: "#95e1d3", text: "#95e1d3"},
          ]

          var optsSelect2 = {
            placeholder: $el.attr("data-value"),
            minimumInputLength: $el.attr("data-minimum-input-length"),
            allowClear: $el.attr("data-allow-blank") == "1",
            multiple: $el.attr("data-multiple") == "1",
            // Display the actual color next to the hex value of the color
            formatResult: function (item) { return "<span style='padding-left: 20px; border-left: 20px solid " + item.text + "'>" + item.text + "</span>"; },
            formatSelection: function (item){ return item.text; },
          };
          
          $el.editable({
            // Source data for list of colors, as array of objects
            source: colorsource,
            params: overrideXeditableParams,
            // select2-specific options
            select2: optsSelect2,
          });

          return true;
...

Suggestion : 4

Updated: September 25, 2015

class MyModelView(BaseModelView):
   column_editable_list = ('question', 'details', 'status')
Traceback (most recent call last):
File "/srv/nerdwallet/myproject/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
...
File "/srv/nerdwallet/myproject/venv/lib/python2.7/site-packages/wtforms/fields/core.py", line 149, in __call__
return self.meta.render_field(self, kwargs)
File "/srv/nerdwallet/myproject/venv/lib/python2.7/site-packages/wtforms/meta.py", line 53, in render_field
return field.widget(field, **render_kw)
File "/srv/nerdwallet/myproject/venv/lib/python2.7/site-packages/flask_admin/model/widgets.py", line 93, in __call__
kwargs = self.get_kwargs(subfield, kwargs)
File "/srv/nerdwallet/myproject/venv/lib/python2.7/site-packages/flask_admin/model/widgets.py", line 148, in get_kwargs
raise Exception('Unsupported field type: %s' % (type(subfield),))
Exception: Unsupported field type: <class 'flask_admin.contrib.sqla.fields.QuerySelectMultipleField'>
class MyModel(AAAModel):
   ...
   # uselist = True means you can have more than one child MyChildModel per MyModel
children = relationship('MyChildModel', secondary = 'model_children_join', uselist = True)
from flask.ext.admin.model.widgets
import XEditableWidget

class CustomWidget(XEditableWidget):

   def get_kwargs(self, subfield, kwargs):
   if subfield.type == 'QuerySelectMultipleField':
   kwargs['data-type'] = 'checklist'
kwargs['data-placement'] = 'left'
# copied from flask_admin / model / widgets.py
choices = {}
for choice in subfield:
   try:
   choices[str(choice._value())] = str(choice.label.text)
except TypeError:
   choices[str(choice._value())] = ""
kwargs['data-source'] = choices
else:
   super(CustomWidget, self).get_kwargs(subfield, kwargs)
return kwargs

class CustomFieldList(ListEditableFieldList):
   widget = CustomWidget()

class MyModelView(BaseModelView):
   column_editable_list = ('question', 'details', 'slug', 'status', 'children')

def get_list_form(self):
   return self.scaffold_list_form(CustomFieldList)