Personal tools
You are here: Home Documentation Tutorials Navigating To Transient Objects Tutorial Creating Objects Based on Form Input

Creating Objects Based on Form Input

What if we wanted the user to be able to designate which Natural object was instantiated for display on this web page?
Thanks to the magic of this database, your web apps can create Python objects that are automatically saved to disk and are available every time your application runs. In particular, every grok.Model and grok.Container object you generate can be written safely to your application's Data.fs file. But sometimes you need to create objects that do not persist in the ZODB, wonderful though it is.
Page 6 of 9.

This is a very common need when implementing things like a database search form, where the user's search terms need to be provided as inputs to the object that will return the search results.

The answer is given in the main Grok tutorial: if you can write your update() method so that it takes keyword parameters, they will be filled in with any form parameters the user provides. Rewrite your to look like:

import grok, random
from transient.natural import Natural

class TransientApp(grok.Application, grok.Container):

class Index(grok.View):
    def update(self, n=None):
        self.badnum = self.num = None
        if n:
                self.num = Natural(int(n))
                self.badnum = n

And make your app_templates/ look like:

 <p tal:condition="view/badnum">This does not look like a natural number:
  &ldquo;<b tal:content="view/badnum">string</b>&rdquo;
 <p tal:condition="view/num">
  You asked about the number <b tal:content="view/num">x</b>!<br/>
  <span tal:condition="view/num/is_prime">It is prime.</span>
  <span tal:condition="view/num/is_composite">Its prime factors are:
   <span tal:repeat="factor view/num/factors">
    <b tal:content="factor">f</b
    ><span tal:condition="not:repeat/factor/end">,</span>
 <form tal:attributes="action python:view.url()" method="GET">
  Choose a number: <input type="text" name="n" value="" />
  <input type="submit" value="Go" />

This time, when you restart your Grok instance and look at your application front page, you will see a form asking for a number:

Choose a number: __________  [Go]

Enter a positive integer and submit the form (try to choose something with less than seven digits to keep the search for prime factors short), and you will see something like:

You asked about the number 48382!
Its prime factors are: 2, 17, 1423
Choose a number: __________  [Go]

And if you examine the URL to which the form has delivered you, you will see that the number you have selected is part of the URL's query section:


So none of these numbers get their own URL; they all live on the page /app/index and have to be selected by submitting a query to that one page.