Search code examples
djangoformsrenderer

django forms - getting django to build the form you want


class BaseForm(forms.Form):
    def as_custom_table(self):
        "Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
        return self._html_output(
            normal_row = u'<tr%(html_class_attr)s><td class="label_col">%(label)s</td><td class="field_col">%(field)s%(help_text)s</td></tr>',
            error_row = u'<tr><td colspan="2" class="error">%s</td></tr>',
            row_ender = u'</td></tr>',
            help_text_html = u'<br />%s',
            errors_on_separate_row = True)

I'm trying to see if I can get django to do the heavy lifting and render a form in the way I want it to render.

The problem here is, there might be one or two fields that need to render slightly differently. Such as a "please confirm you agree to our terms and conditions" check box, which would need to span two columns.

Also some other things, such as error placement, might need changing.

I could override the _html_output method to change error placement, but what about getting an individual field to use a different render method?

I think ultimately I need to revert to manually building the form html in the template, but I'm just wondering how much of it Django could do for me with some minor modifications.


Solution

  • The suggested method will be to use a template like this:

    <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>
    

    You can conditionally override specific fields using {{ if field.my_property }}.