1

I really like the ability to use modelforms in django to speed up UI. IE:

<html>
    ...
    {{ myform }}
    ...
</html>

However, the HTML output I need to create does not match what is created by default. I cannot change my required HTML output, but I would like to change the output of the form.

I know that there are a few approaches to doing so. Looping over the fields and displaying each one individually (i.e. looping and displaying {{ myform.field }} ) works ok, but it's not nearly as nice as just doing {{ myform }}. Widgets seemed like a good idea, but after looking at the docs & some examples, I am not so sure - I just want to change the html output, not the functionality. If there WAS some way to output a field based perhaps on a template, that would be nice.

Any ideas?

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
arcologies
  • 742
  • 1
  • 6
  • 22

1 Answers1

3

I usually use the include tag. I create a custom template (form_snippet.html).

For the sake of argument let's say the form_snippet.html just prints the form:

<!-- Form snippet -->
{{ form }}

Then when you want to use that form template in your other templates you simply have to use:

{% include 'form_snippet.html' with form=myform %}

You could simply loop over fields and add your custom markup.

D.A
  • 2,555
  • 1
  • 14
  • 10
  • Great idea, thanks. To add to this, I needed to distinguish between different field types - this: http://stackoverflow.com/questions/1809874/get-type-of-django-form-widget-from-within-template/1809982 worked nicely for me. – arcologies Aug 09 '12 at 02:53
  • 1
    Excellent! Something about dead simple template filters makes me smile. – D.A Aug 09 '12 at 02:55