kvesteri / wtforms-alchemy

Tools for creating wtforms from sqlalchemy models
Other
245 stars 59 forks source link

Better Flask-admin support #149

Open Altiire opened 5 years ago

Altiire commented 5 years ago

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 commented 5 years ago

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