tiktuk
tiktuk

Reputation: 495

Flask-Admin: Custom Query for Select Field with Peewee?

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 )

Upvotes: 0

Views: 1499

Answers (1)

tiktuk
tiktuk

Reputation: 495

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)

Upvotes: 1

Related Questions