[Grok-dev] Multiple models inside container

Martijn Faassen faassen at startifact.com
Wed Mar 23 19:06:13 EDT 2011

On 03/23/2011 01:24 PM, Lumir Jasiok wrote:

> OK, I understand concept and I like it. This is what I looking for. But
> I am not familiar with grok.traversable(). Sorry for trouble you, but do
> you have some small example? Will be possible edit objects inside
> container using EditForm?

Yes, it won't matter where the objects are, as long as the EditForm's 
context is the objects you want to edit, it should work.

> AFIK grok.context() inside EditForm should be
> just Application or Model object types?

Generally for an edit form you'd want the context to be the object you 
want to edit, and for an add form you'd want the context to be the 
collection (container) of objects you want to add to.

For an example, check here:


but for containers, you'd basically do this:

class MyApplication(grok.Application, grok.Model):

     def __init__(self):
          self.foo = FooContainer()
          self.bar = BarContainer()

Now myapp/foo and myapp/bar are your containers. You'd probably have add 
forms like this: myapp/foo/add and myapp/bar/add, and you'd have edit 
forms like this myapp/foo/1553/edit and myapp/bar/515353/edit. You'd 
make the add form for 'Foo' objects the context of FooContainer, and the 
same for bar and BarContainer.

Note that as I said previously, you might need an event to set up these 
containers instead, I'm not sure initialization will go nicely here - 
not 100% sure.

You could also choose to let MyApplication itself be a container, in 
which case you wouldn't need grok.traversable:

class MyApplication(grok.Application, grok.Container):
     def __init__(self):
          self['foo'] = FooContainer()
          self['bar'] = BarContainer()

but this design is a bit less nice, as really the application isn't 
really a container people can add and remove things to.

> This code doesn't work. Problem is with isinstance(store,Store)
> evaluation. It always failed. I tried isinstance(store,context/Store)
> without success. Only working code is isinstance(store,object). But this
> is useless. How can I test if repeated object is Store or Employee
> object correctly inside page templates?

I would never do this within a template. I'd always write a helper 
method in Python to do this, and then call this from your template 
instead. I'd simply make a method that returns all stores. That makes it 
easier to test too. Page templates are restricted in various ways that I 
just don't want to have to deal with. In this case I don't know where 
the 'Store' class comes from in the template.

But anyway, if you change your application's design so that the stores 
are in a separate container, things will become simpler.



More information about the Grok-dev mailing list