0

I have a model with a ForeignKeyField which gets rendered as a select field in the create/edit form in Flask-Admin. I would like to restrict the choices in the select field with a custom query so the user only has access to their own source addresses.

All answers point I've found point in the direction of WTForms' QuerySelectField but that is only for SQLAlchemy and I am using Peewee.

It seems like a pretty common thing to do though, so any other way?

class BulkMessage(BaseModel): title = CharField(null=True) source_address = ForeignKeyField( SourceAddress, related_name='bulk_messages', null=True )

1 Answer 1

1

It is pretty simple, actually:

Just override edit_form in the ModelView and create the field there with the query passed in choices, as seen in the docs:

def edit_form(self):
    form = model_form(BulkMessage)

    form.source_address = SelectField(
        'Source Address',
        choices=[(sa.id, sa.title) for sa in SourceAddress.select().where(SourceAddress.owner == current_user.id)]
    )

    return form(obj=obj)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.