2

forms.py

my_field = TextField(u"Enter a number", validators=[Required('This Field is Required')])

my_form.html

<table>
  <tr>
    <td colspan="4"> 
      {{form.my_field(placeholder= form.my_field.label.text, class_="form-control")}}
      {% for error in form.my_field.errors %}
          <span>{{error}}</span>
      {% endfor %}
    </td>
  </tr>
</table>

This is a simple code. But I want to follow kind of this to render all the input fields in a loop instead of writing the code for each of them. But each field will have a different colspan value in the corresponding <td>.

How can I add a custom parameter for colspan which I can use in the <td>?

Something like: (just the diff from above code)

forms.py

my_field = TextField(colspan="4")

my_form.html

<td colspan={{form.my_field.colspan}}>
Community
  • 1
  • 1
RatDon
  • 3,403
  • 8
  • 43
  • 85

1 Answers1

2

You need to create a custom field with an extra colspan attribute.

First define the custom field sub classing TextField:

class MyCustomTextField(TextField):
    def __init__(self, colspan=4, *args, **kwargs):
        super(MyCustomTextField, self).__init__(*args, **kwargs)
        self.colspan = colspan

Now use the custom field in your form:

class MyForm(Form):
    my_field = MyCustomTextField(4, u"Enter a number", validators=[Required('This Field is Required')])

See that first parameter (a 4 in this case) for MyCustomTextField? That's your colspan attribute.

Finally, access the attribute in your template like so:

<td colspan="{{form.my_field.colspan}}">
AArias
  • 2,558
  • 3
  • 26
  • 36
  • This custom class is a good idea which I always forget. But in this case, I need to create a common custom class for all the fields. Not just the `TextField` as in my case I've more than 20 form fields with nearly all types of input fields available out there. Is it possible to create something like that? – RatDon Sep 17 '16 at 11:00
  • 1
    That's a tough one. I have been messing around for a while trying to sub class the parent `Field` class and then trying to change the parent class of other fields grabbing some ideas from this other answer: http://stackoverflow.com/a/9541560/3632543 But I wasn't successful at it, plus it is mentioned it is not really a good idea to do. The easiest (although I understand is kinda clumsy) way to do this would be to just define your own set of fields, sub classing each field you need. I know it's quite a bit of code to write but should be a one time job and pretty straight forward. – AArias Sep 17 '16 at 11:44
  • 1
    Yeah. It will be a one time job only and can use it in future usage also. Thanks. – RatDon Sep 19 '16 at 05:08