Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better Flask-admin support #149

Open
Altiire opened this issue Sep 3, 2019 · 1 comment
Open

Better Flask-admin support #149

Altiire opened this issue Sep 3, 2019 · 1 comment

Comments

@Altiire
Copy link

Altiire commented Sep 3, 2019

Hi,

I managed to generate forms by overriding the form generation of a ModelView.
But before that, I could update my foreign keys with a dropdown on the relationship. I managed to include the foreign keys with the option but I need to manually set their values.

I did not find a solution for a generic based relationship generation under the documentation.

sample of my admin/views.py

from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView

from supervisor import models
from wtforms_alchemy import ModelForm

class AdminModelView(ModelView):
    def is_accessible(self):
        return current_user.is_authenticated

    def scaffold_form(self):


        class AdminModelForm(ModelForm):
            class Meta:
                model = self.model
                include_foreign_keys = True

        return AdminModelForm


def init_admin(app, db):
    admin = Admin(app, name='Flowlity')
    admin.add_view(AdminModelView(models.Company, db.session))
@Altiire
Copy link
Author

Altiire commented Sep 11, 2019

In addition, I had to rewrite create_model for a special case:
I have a nullable foreign_key of type UUIDType, if the field is not filled in the form, an empty string is sent. This empty string is then parsed by python's uuid.UUID and raise a ValueError exception.

Here is my quick fix:

    def create_model(self, form):
        try:
            model = self.model()
            if isinstance(model, models.Supply):
                form.populate_obj(model)
                self.session.add(model)
                self.on_model_change(form, model, True)
                model.contact_id = None
                self.session.commit()
            else:
                return super().create_model(form)
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')
                logging.getLogger('flask-admin.sqla').exception('Failed to create record.')
            self.session.rollback()
            return False
        else:
            self.after_model_change(form, model, True)
        return model

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant