Displaying forms

Django forms also help you create an HTML representation of your form. They support three different representations: as_p (as paragraph tags), as_ul (as unordered list items), and as_table (as, unsurprisingly, a table).

The template code, generated HTML code, and browser rendering for each of these representations have been summarized in the following table:

Template

Code

Output in Browser

{{ form.as_p }}
<p><label   for="id_name">Name:</label> <input type="text" name="name"   maxlength="100" required id="id_name" /></p>   
<p><label   for="id_age">Age:</label> <input type="number" name="age"   required id="id_age" /></p>   

{{ form.as_ul }}

<li><label   for="id_name">Name:</label> <input type="text" name="name"   maxlength="100" required id="id_name" /></li>   
<li><label   for="id_age">Age:</label> <input type="number" name="age"   required id="id_age" /></li>   

{{ form.as_table }}

<tr><th><label   for="id_name">Name:</label></th><td><input type="text"   name="name" maxlength="100" required id="id_name" /></td></tr>   
<tr><th><label   for="id_age">Age:</label></th><td><input type="number"   name="age" required id="id_age" /></td></tr>   

Note that the HTML representation gives only the form fields. This makes it easier to include multiple Django forms in a single HTML form. However, this also means that the template designer has a fair bit of boilerplate to write for each form, as shown in the following code:

<form method="post"> 
  {% csrf_token %} 
  <table>{{ form.as_table }}</table> 
  <input type="submit" value="Submit" /> 
</form> 
To make the HTML representation complete, you need to add the surrounding form tags, a csrf_token, the table or ul tags, and the Submit button.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.218.230