Getting SelectField to populate with all choices and saved DB value selected on Edit form

16 Views Asked by At

I am trying to pull the database data into the EditTicketForm with the SelectField drop down list populated with all of the valid choices and the saved value selected.

forms > ticket.py

class CreateTicketForm(StarletteForm):
...
    category_id = SelectField(
        'Category',
        coerce=int,
        validators=[DataRequired('Category Required')],
    )

class EditTicketForm(CreateTicketForm):
    pass

models > ticket.py

class Ticket(Base):
    __tablename__ = 'tickets'
...
    category_id: Mapped[int] = mapped_column(
        ForeignKey("ticket_categories.id"),
        nullable=True)
    
    category: Mapped['TicketCategory'] = relationship(
        'TicketCategory',
        back_populates='ticket'
    )

The CreateTicketForm correctly builds the Category drop down and the category_id, along with the rest of the form data, is correctly saved into the database.

How the CreateTicketForm is displayed

The EditTicketForm will build without errors, with the rest of the form data correctly displayed. However the Category drop down is not populated with the valid choices or with the saved value.

How the EditTicketForm is displayed

Here is the code within the @router.get


form.title.data = ticket.title
form.body.data = ticket.body
form.category_id.choices = [(category.id, category.name) for category in ticketCategory]
form.category_id.data = ticket.category_id

form = EditTicketForm(
    request=request,
    title=ticket.title,
    body=ticket.body,
    category_id=ticket.category_id)

0

There are 0 best solutions below