Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Table-based formset rendering
{% load crispy_forms_field %}
{% if field.is_hidden %}
{{ field }}
{% else %}
{% crispy_field field %}
{% endif %}
from crispy_forms.utils import render_field
from django.template.loader import render_to_string
from django.template import Context
class BaseTable(object):
template = "forms/layout/table_elems.html"
def __init__(self, *fields, **kwargs):
self.fields = fields
if hasattr(self, 'css_class') and 'css_class' in kwargs:
self.css_class += ' %s' % kwargs.get('css_class')
if not hasattr(self, 'css_class'):
self.css_class = kwargs.get('css_class', None)
self.css_id = kwargs.get('css_id', '')
self.template = kwargs.get('template', self.template)
def render(self, form, form_style, context):
fields = ''
for field in self.fields:
fields += render_field(field, form, form_style, context)
return render_to_string(self.template, Context({'tag': self.element,
'elem': self,
'fields': fields}))
class TD(BaseTable):
element = 'td'
class TR(BaseTable):
element = 'tr'
# And this is how I use these elements
class DetailForm(ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.help_text_inline = True
self.helper.form_class = 'form-horizontal'
self.helper.form_tag = False
self.helper.layout = Layout(
TR(
'id',
TD(
Field('status', css_class='part-type',
template="forms/field.html"),),
TD(
Field('cantidad', css_class='span1',
template="forms/field.html"),),
TD(
Field('precio_preferencial', css_class='ref-price',
template="forms/field.html"),),
TD(
Field('calidad', css_class='',
template="forms/field.html"),),
TD(
Field('num_parte', css_class='part-number',
template="forms/field.html"),),
TD(
Field('descripcion', rows='3', columns='20',
css_class='', template="forms/field.html"),),
TD(
Field('cotizar', css_class='span1',
template="forms/field.html"),
css_class='price-list'
),
TD(
Field('image', css_class='file-input',
template="forms/imagefield.html"),
),
TD(
Field('DELETE', template="forms/field.html")
),
css_class='detail-form',
)
)
super(DetailForm, self).__init__(*args, **kwargs)
class Meta:
model = Detail
<{{tag}} {% if elem.css_id %}id="{{ elem.css_id }}"{% endif %}
{% if elem.css_class %}class="{{ elem.css_class }}"{% endif %}>
{{ fields|safe }}
</{{tag}}>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.