Re: how to write a custom renderer for any relationship ?

49 views
Skip to first unread message

Bruk Habtu

unread,
Jun 13, 2013, 4:24:34 PM6/13/13
to forma...@googlegroups.com
Renderers have two methods you can override. render and render_readonly. You can have your custom renderer inherit the SelectFieldRenderer and override it's render_readonly method so that it returns a link.



def render_readonly(self, options=None, **kwargs):
    #build a dict
    if callable(options):
        L = options(self.field.parent)
    else:
        L = list(options)

    if len(L) > 0:
       if len(L[0]) == 2:
           L = [(v, k) for k, v in L]
       else:
           L = [(k, _stringify(k)) for k in L]    
    D = dict(L)
    links = []
    for key, val in D.iteritems():
        links.append("<a href='{0}'>{1}</a>".format(value, key))
    return '<br/>'.join(links)

Just quickly wrote that up, not sure if it works or not as I am at work and dont have time to test it but that should give you an idea of what to do. 

As for a default renderer, there doesn't look like there is a ForeignKey key you can use. The keys available are column types and don't include constraints.

On Friday, 26 October 2012 10:17:15 UTC-4, pca wrote:
Hi,

I'm trying to write a simple admin site for the cherrypy web framework.  I wish to show foreign keys as a list box in edit mode (easy), and as a link to another admin web page in read-only mode (very hard !).  I would think that this is a very common requirement, but I still can't find a way to do it with formAlchemy in a generic way. Could someone help ?

The basic program outline is as follows.  Let's say I have 2 tables A and B, and A.b_id is a foreign key to B.id

class A(Base):
    __tablename__ = 'A'
    id = Column(Integer, primary_key=True)
    b_id = Column(Integer, ForeignKey('B.id''))
    b = relationship("B")

class B(Base):
    __tablename__ = 'B'
    id = Column(Integer, primary_key=True)
   
a = session.query(A).filter(id == 123).first()
fs = FieldSet(a)
fs.readonly = True # or false
print fs.render()

a.b is an instance of the B class : it is rendered as a list box in edit mode, and as a string in readonly mode.

How to render a.b as an HTML link in readonly, while keeping it as a list box in edit mode ?  How to do this in a generic way, for any relationship ?  I have tried to add a custom renderer to the DefaultRenderers dictionary, but which key should I use for a relationship renderer ?

Thanks in advance.
Pierre C.
Reply all
Reply to author
Forward
0 new messages