pallets-eco / flask-admin

Simple and extensible administrative interface framework for Flask
https://flask-admin.readthedocs.io
BSD 3-Clause "New" or "Revised" License
5.8k stars 1.58k forks source link

Having a list field in flask-admin page #1491

Open gurditsbedi opened 7 years ago

gurditsbedi commented 7 years ago

I'm making a admin dashboard for a MongoDB, I'm using pymongo. I want to have a list field, and do CRUD operations on it plus the Create,Update operation is limited to choices(using select2field). How can I do this?

I have posted the question on stackoverflow. https://stackoverflow.com/questions/44347462/list-field-in-flask-admin-crud-operations-from-flask-admin-on-a-specific-mongod I didnt go a response till now though. It is defined with an example there.

ljluestc commented 5 months ago

from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.mongoengine import ModelView
from flask_admin.form import Select2Field
from wtforms.fields import SelectField
from wtforms.validators import InputRequired
from flask_mongoengine.wtf import model_form

# Custom form with Select2Field for 'role'
class UserForm(model_form(User)):
    role = Select2Field('Role', validators=[InputRequired()], choices=[])

class UserView(ModelView):
    column_list = ('name', 'role')
    form = UserForm

    def on_model_change(self, form, model, is_created):
        model.role = form.role.data

    def create_form(self, obj=None):
        form = super(UserView, self).create_form(obj=obj)
        form.role.choices = [(choice, choice) for choice in ['Admin', 'Editor', 'Viewer']]
        return form

    def edit_form(self, obj=None):
        form = super(UserView, self).edit_form(obj=obj)
        form.role.choices = [(choice, choice) for choice in ['Admin', 'Editor', 'Viewer']]
        return form

admin = Admin(app, name='Flask Admin Example', template_mode='bootstrap3')
admin.add_view(UserView(User))