[Django]-Django: How to make a form with custom templating?

22👍

<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 find the complete documentation here:
http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template

10👍

I don’t think you need a formset here. Take a look here if you want a custom template for one view. If you want to create your own {{ form.as_foobar }}, just subclass forms.Form, something like this:

class MyForm(forms.Form):
  def as_foobar(self):
    return self._html_output(
      normal_row = u'%(label)s %(field)s%(help_text)s',
      error_row = u'%s',
      row_ender = '',
      help_text_html = u' %s',
      errors_on_separate_row = False)

and just use it in your forms.py:

class ContactForm(MyForm):
  # ..
👤Bjorn

4👍

For whoever needs the <table> version of jbcurtin’s answer:

<form method="post">{% csrf_token %}
  <table>
    {% for field in form %}
      <tr>
        <th>{{field.label_tag}}</th>
        <td>
          {{ field.errors }}
          {{ field }}
        </td>
      </tr>
    {% endfor %}
  </table>
  <hr/>
  <input type="submit" value="Conferma" />
</form>

1👍

Looks like you might be interested in django-floppyforms (docs), which gives you much more control over field rendering.

Leave a comment