Personal tools
You are here: Home Documentation Tutorials Working with Forms in Grok Introducing Forms

Introducing Forms

An overview of the Form infrastructure in Grok
A walkthrough of the basics of automatically generating HTML forms using Grok, as well as a discussion of a few more advanced Form manipulations.
Page 1 of 9.

When working with HTML Forms in Grok, they are simply treated as a special type of View. The Form base class inherits from grok.View.

Just like you might make a simple View for an Application:

class MammothApplication(grok.Application, grok.Container):
    """World's greatest Mammoth manager web application."""

class Index(grok.View):
    def render(self):
        return "Augh! The application, it does nothing!"

You can replace the default View with a Form View.

class Index(grok.Form):
    "An empty Form"

This will render a complete - albiet completely empty - form. The default HTML rendered for a blank form will look like:

<html>
<head>
<base href="http://localhost:8080/mammoth/@@index" />
</head>

<body>

<form action="http://localhost:8080/mammoth/@@index"
      method="post" class="edit-form"
      enctype="multipart/form-data">

  <table class="form-fields">
    <tbody>
        <tr>
          <td class="label">
          </td>
          <td class="field">
          </td>
        </tr>
    </tbody>
  </table>

  <div id="actionsView">
  </div>

</form>

</body>
</html>

Forms provide the ability to customizing the template used to generate the HTML, as well as for handling the label of the form, the fields of a form, buttons of a form, the action that gets called when a form is submitted, and finally a way to automatically generate forms for creating and editing your Model objects.

Forms in Grok let you create complete working HTML Forms with very little code. Let's look at a more complete example:

class Edit(grok.EditForm):
    form_fields = grok.AutoFields(Mammoth)
    label = 'Edit Mammoth'

    @grok.action('Edit Mammoth')
    def edit(self, **data):
        self.applyData(self.context, **data)
        self.redirect(self.url(self.context))

In a short 7 lines of code this produces a complete working form that allow you to edit a Mammoth model object. When this form is viewed it looks like:

makemammoth.jpg

However, there are a lot of use-cases for working with forms, and this tutorial is intended to guide you through the many ways you can make the Grok Forms work towards what you want your application to do.