[Django]-Editing Django _form.as_p

49πŸ‘

βœ…

You simply just can’t use form.as_p anymore. If the defaults don’t work for you, then you must render the fields manually:

<form action="/contact/" method="post">
    {% for field in form %}
        <div class="fieldWrapper">
            {{ field.errors }}
            {{ field.label_tag }}: {{ field }}
        </div>
    {% endfor %}
    <p><input type="submit" value="Send message" /></p>
</form>

See the docs: https://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields

πŸ‘€Chris Pratt

7πŸ‘

If you just need a break, then there’s no need to change the Django code. Just use CSS to style label as display: block.

7πŸ‘

Override as_p on your form class.

class MyForm(forms.Form):
    def as_p(self):
        "Returns this form rendered as HTML <p>s."
        return self._html_output(
            normal_row = u'<p%(html_class_attr)s>%(label)s</p> %(field)s%(help_text)s',
            error_row = u'%s',
            row_ender = '</p>',
            help_text_html = u' <span class="helptext">%s</span>',
            errors_on_separate_row = True)

3πŸ‘

Pretty much what Brian describes above. I would write a new method for your form like as_myp. I made this for myself. I took as_table method and made as_plain to remove the tr/th markups. Ex.

class MyForm(forms.Form):
    my_field1 = forms.CharField(...)
    my_field2 = forms.WhateverField(...)

    def as_myp(self):
        "Returns this form rendered as HTML <p>s."
        return self._html_output(
            normal_row = '<p%(html_class_attr)s>%(label)s</p> <p>%(field)s%(help_text)s</p>',
            error_row = '%s',
            row_ender = '</p>',
            help_text_html = ' <span class="helptext">%s</span>',
            errors_on_separate_row = True)

    def as_plain(self):
        "Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
        return self._html_output(
            normal_row = '%(label)s%(errors)s%(field)s%(help_text)s',
            error_row = '%s',
            row_ender = ' ',
            help_text_html = '<br /><span class="helptext">%s</span>',
            errors_on_separate_row = False)

It just seemed easier to do that than write a template file and handle form field rendering with errors, tags, visible/hidden, etc.

πŸ‘€Al Conrad

-6πŸ‘

Template:

<div id="my_form">
    {{ form.as_p }}
</div>

CSS:

#my_form p label,
#my_form p input{
    float: left;
    clear: left;
}

So if you add fields you can still use form.as_p

πŸ‘€Gromish

Leave a comment