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

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

Open
kopax-polyconseil opened this issue Apr 6, 2021 · 1 comment

Comments

@kopax-polyconseil
Copy link

kopax-polyconseil commented Apr 6, 2021

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
Copy link

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.

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

No branches or pull requests

2 participants