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

How can I query the database to fill my model using `on_model_change`? #2102

Open kopax-polyconseil opened 3 years ago

kopax-polyconseil commented 3 years ago

I am calling the following on_model_change:

def on_model_change(self, form: Form, model: ApiKey, is_created: bool) -> None:
    if is_created:
        try:
            offerer = find_by_siren(form.offererSiren.data)
            if offerer is not None:
                print('OK===========')
                model.value = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(64))
                model.offererId = offerer.id
            else:
                print('NOK===========')
        except:
            print('Unexpected error', sys.exc_info())
            raise

    super().on_model_change(form, model, is_created)

This cause the following error:

Unexpected error (<class 'sqlalchemy.exc.IntegrityError'>, IntegrityError('(psycopg2.errors.NotNullViolation) null value in column "offererId" violates not-null constraint\nDETAIL:  Failing row contains (15, null, null).\n'), <traceback object at 0x7f8dd1ecd870>)

This is probably because of: https://github.com/flask-admin/flask-admin/blob/e764f6f0be3facbefb2b4d30b5c3f2f2c630d530/flask_admin/contrib/sqla/view.py#L1141

How can I query the database to fill my model using on_model_change?

amendocrem commented 1 year ago

I'm struggling with this today.

On after_model_change I can do a query to db, so my solution was fill the field with any value and then change that field using after_model_change.

Not the best solution, but it works.