liveBook · Manning

Form.as_p

As explained in Django in Action

form.as_p is a Django Form method that renders form fields wrapped in HTML paragraph elements.

form.as_p is a Django Form method that renders every form field inside an HTML <p> element. In a template, {{ form.as_p }} quickly produces usable labels, inputs, textareas, required attributes, IDs, names, and validation-ready markup. section 7.1

It is a convenient starting point rather than a design system. CSS can improve the appearance, while Bootstrap-style layouts usually require writing the surrounding HTML yourself and preserving Django’s expected name and id attributes. section 7.1.3

Inspecting rendered output

Create a CommentForm, then run print(f.as_p()) in the Django shell. A name field becomes a label and input inside one paragraph; a comment field becomes a label and textarea inside another. Widget attributes such as rows and cols appear in the generated textarea. section 7.1

>>> from content.forms import CommentForm
>>> f = CommentForm()
>>> print(f.as_p())
<p>
    <label for="id_name">Name:</label>
    <input type="text" name="name" required id="id_name">
</p>
<p>
    <label for="id_comment">Comment:</label>
    <textarea name="comment" cols="50" rows="6" required
        id="id_comment"></textarea>
</p>

View the concrete HTML produced by CommentForm.as_p(), including labels, controls, required attributes, IDs, names, and textarea dimensions. section 7.1

How Django in Action covers it

How deep it goes
Defines the generated wrappers and common attributes, but stops short of custom Bootstrap layouts and full hand-written HTML.
Examples
Uses CommentForm output in the Django shell, including paragraph-wrapped name and comment fields.
What it assumes
Assumes familiarity with Django Form objects and templates while demonstrating the generated HTML from a simple form.
What you can do after
Apply it via Django forms to render a basic form without hand-writing each field’s HTML.
How it connects
Links Django forms with widgets, HTML labels and controls, CSS styling, and Bootstrap markup.

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.