[Grok-dev] Re: Adding a image to form_fields

Philipp von Weitershausen philipp at weitershausen.de
Wed Aug 29 16:15:21 EDT 2007


Jan Ulrich Hasecke wrote:
> I want to add images to my animal objects in our zoo game. I want to 
> access them in page templates via "context.icon" eg. or any other better 
> method.
> 
> The images reside in static.

That means they're resources. I don't think it would be wise having to 
make them directly accessible via an attribute on the model (e.g. 
"context.icon").

> How do I add them?
> 
> I have an animal class and want to make subclasses for each breed. When 
> an animal of a selected breed is added the predefined image shall be 
> assigned to the object. But how?
> 
> In the Addform? Or in the class/subclass itself?
> 
> And what do I have to define in form_fields?

A dead simple version:

   import os
   import glob

   path = os.path.dirname(__file__)
   image_choices = glob.glob(os.path.join(path, 'static', '*.jpg'))

> form_fields = grok.Fields(
>     name=TextLine(title=u"Name"),
>     age=Int(title=u"Alter"),
>     price=Int(title=u"Preis"))
>     image=…

       image = Choice(title=u'Bild', values=image_choices)

This will present the user with a drop down list of image filenames. If 
you want something more comfortable, consider writing a vocabulary where 
the items of the dropdown list can have pretty titles instead of the raw 
values. My book explains how to do that ("Sources and Vocabularies" 
chapter).

The model will receive have an 'image' attribute now, containing the 
filename of the image selected. We can use this in the PageTemplate then:

   <img src="" tal:define="filename context/image
               tal:attributes="src static/?filename" />


-- 
http://worldcookery.com -- Professional Zope documentation and training


More information about the Grok-dev mailing list