Deform default not working as expected with Class

134 views Asked by At

I am using the deform form plugin with pyramid.

I first of, have my model:

class Manufacturer(Base):
    __tablename__ = 'manufacturers'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode, nullable=False, unique=True)
    image_id = Column(Integer, ForeignKey('images.id'))
    product = relationship('Product', backref='manufacturer')

    @classmethod
    def _choices(cls):
        choices_query = DBSession.query(cls).\
        order_by(asc(Manufacturer.name)).all()
        return [(ch.id, ch.name) for ch in choices_query]

Now in my view I have the deform code, this works fine for adding new entries.

class EditMattingSchema(colander.MappingSchema):
    name = colander.SchemaNode(colander.String(),
           default=product.name)

    manufacturer = colander.SchemaNode(colander.String(),
        widget = widget.SelectWidget(values=Manufacturer._choices()))

Now this generates my html correctly and the select box renders perfectly.

However, when I use a default option, such as:

product = Session.query(Product).\
    filter(Product.slug == 'foo').first()

default_id = product.manufacturer_id
print default_id
1

manufacturer = colander.SchemaNode(colander.String(),
    default = default_id
    widget = widget.SelectWidget(values=Manufacturer._choices()))

The html rendered does not add a

selected="selected"

To my default input box (or to any option, even if I hard code it in, replacing the variable name with the value that should be the default choice).

1

There are 1 answers

0
crooksey On

I had to update my class method to return integer values as strings, even though this is not required if I define choices manually, as shown in the deform demo:

@classmethod
    def _choices(cls):
        choices_query = DBSession.query(cls).\
        order_by(asc(Manufacturer.name)).all()
        return [(str(ch.id), ch.name) for ch in choices_query]