Dynamic Django form not only with inputs
I haven't used Django for long and I have a dynamic Django form:
class GoodsAddPropertyForm(forms.Form):
def __init__(self, groups_and_properties, *args, **kwargs):
super(GoodsAddPropertyForm, self).__init__(*args, **kwargs)
for group_and_properties in groups_and_properties:
self.fields[group_and_properties.name] = CharField(label = group_and_properties)
for property in group_and_properties.properties:
if property.type == 'boolean':
开发者_如何转开发self.fields[property.name] = forms.BooleanField(label = property.name, required=False)
elif property.type == 'float':
self.fields[property.name] = forms.FloatField(label = property.name)
How can I make that self.fields[group_and_properties.name]
= CharField(label = group_and_properties)
will be a simple HTML text without an input element?
Define a custom widget:
from django.utils.safestring import mark_safe
class HTMLWidget(forms.widgets.Widget):
def render(self, name, value, attrs=None):
output = []
output.append('<p>Hello world: %s</p>' % value)
return mark_safe(u''.join(output))
The specify it as your CharField widget:
self.fields[group_and_properties.name] = CharField(label = group_and_properties, widget = HTMLWidget())
You should look at forms.MultiValueField and forms.MultiWidget. But it doesnt fine, so you have to subclass them.
精彩评论