- Author:
- flashingpumpkin
- Posted:
- September 17, 2009
- Language:
- Python
- Version:
- 1.1
- Score:
- 3 (after 3 ratings)
This a mixin that can be used to render forms from predefined templates instead of using .as_table / .as_p / .as_ul
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | class TemplateForm(object):
"""
Mixin to render forms from a predefined template
Example template:
``toolbox/forms/form.html``:
{% if form.errors or form.non_field_errors %}
<tr>
<td colspan="2" class="error">
<div class="form-errors">
<span class="cross"></span>
<div>
<h1>Error</h1>
<ul>
{% for error in form.non_field_errors %}
<li>{{ error }}</li>
{% endfor %}
{% for field in form %}{% for error in field.errors %}
<li>{{ field.label }}: {{ error }}</li>
{% endfor %}{% endfor %}
</ul>
</div>
</div>
</td>
</tr>
{% endif %}
{% for field in form %}
{% include "toolbox/forms/form_field.html" %}
{% endfor %}
``toolbox/forms/form_field.html``:
<tr {% if field.errors %}class="error"{% endif %}>
<th {% if field.field.required %}class="required"{% endif %}>
<label for="{{ field.auto_id }}">{{ field.label.title }}</label>
</th>
<td class="input">
{{ field }}
<div class="help">
{{ field.help_text }}
</div>
</td>
</tr>
"""
@property
def form_class_name(self):
return '.'.join([self.__module__, self.__class__.__name__.lower()])
def as_template(self):
"""
Renders a form from a template
"""
self.template_name = self.__class__.__name__.lower()
if not getattr(self, 'tpl', None):
self.tpl = loader.get_template('toolbox/forms/form.html')
context_dict = dict(
non_field_errors=self.non_field_errors(),
fields=[ forms.forms.BoundField(self, field, name) for name, field in self.fields.iteritems()],
errors=self.errors,
data=self.data,
form=self,
)
if getattr(self, 'initial', None):
context_dict.update(dict(initial=self.initial))
if getattr(self, 'instance', None):
context_dict.update(dict(instance=self.instance))
if getattr(self, 'cleaned_data', None):
context_dict.update(dict(cleaned_data=self.cleaned_data))
return self.tpl.render(
Context(context_dict)
)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.