1. 程式人生 > >Working with forms

Working with forms

end anti ssi con code chan receiving retrieve style

  Unless you’re planning to build websites and applications that do nothing but publish content, and don’t accept input
from your visitors, you’re going to need to understand and use forms.
  Django provides a range of tools and libraries to help you build forms to accept input from site visitors, and then


process and respond to the input.

  Any request that could be used to change the state of the system - for example, a request that makes changes in the
database - should use POST. GET should be used only for requests that do not affect the state of the system.

  Django handles three distinct parts of the work involved in forms:


  ? preparing and restructuring data to make it ready for rendering
  ? creating HTML forms for the data
  ? receiving and processing submitted forms and data from the client
It is possible to write code that does all of this manually, but Django can take care of it all for you.

  In a similar way that a model class’s fields map to database fields, a form class’s fields map to HTML form <input>

elements. (A ModelForm maps a model class’s fields to HTML form <input> elements via a Form; this is what
the Django admin is based upon.)

Instantiating, processing, and rendering forms
When rendering an object in Django, we generally:
  1. get hold of it in the view (fetch it from the database, for example)
  2. pass it to the template context
  3. expand it to HTML markup using template variables
  Rendering a form in a template involves nearly the same work as rendering any other kind of object, but there are some
key differences.
  In the case of a model instance that contained no data, it would rarely if ever be useful to do anything with it in a
template. On the other hand, it makes perfect sense to render an unpopulated form - that’s what we do when we want
the user to populate it.
  So when we handle a model instance in a view, we typically retrieve it from the database. When we’re dealing with a
form we typically instantiate it in the view.
  When we instantiate a form, we can opt to leave it empty or pre-populate it, for example with:
  ? data from a saved model instance (as in the case of admin forms for editing)
  ? data that we have collated from other sources
  ? data received from a previous HTML form submission
  The last of these cases is the most interesting, because it’s what makes it possible for users not just to read a website,

but to send information back to it too.

Form.as_p()
  as_p() renders the form as a series of <p> tags, with each <p> containing one field

Working with forms