动态Django不仅形成输入

时间:2011-01-31 15:37:05

标签: python django django-forms

我没有长时间使用Django,我有一个动态的Django形式:

   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)

如何使self.fields[group_and_properties.name] = CharField(label = group_and_properties)成为没有输入元素的简单HTML文本?

2 个答案:

答案 0 :(得分:1)

定义自定义小部件:

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))

将其指定为CharField小部件:

self.fields[group_and_properties.name] = CharField(label = group_and_properties, widget = HTMLWidget())

答案 1 :(得分:-1)

你应该看看forms.MultiValueField和forms.MultiWidget。但它并不好,所以你必须将它们分类。