mikhail
mikhail

Reputation: 522

Django from JSON format

I try to make custom django form, from JSON format, like this

{
    "1": ["fieldlabel1", "str", false], 
    "2": ["fieldlabel2", "str", false]
}

where 'fieldlabel1' - label of the field, int or str - field type IntegerField or CharField, and the last parameter True or False is field required or not.

FIELD_TYPES = {
    'str': forms.CharField,
    'int': forms.IntegerField,
}

    class ItemsGroup(models.Model):   
        ...
        fields = models.TextField(u'Addtional fields (JSON format)', blank=True, null=True, default=None)

        # raw_fields = { 1: (u'fieldlabel1','int', True), 2: (u'fieldlabel2','str', False) }
        def fields_form(self):
            try:
                raw_fields = json.loads(self.fields)
                fields = {}
                for key in raw_fields.keys():
                    fields['field'+str(raw_fields[key])] = FIELD_TYPES[raw_fields[key][1]](
                        label = raw_fields[key][0], required = raw_fields[key][2]
                    )

                return type('Form', (forms.Form,), fields)

            except ValueError:
                return None

In template, when I do like this: {{ items_group.fields_form }}, receive class 'django.forms.forms.Form', this {{ items_group.fields_form.as_ul }} recieve nothing.

Upvotes: 0

Views: 257

Answers (1)

Anurag Uniyal
Anurag Uniyal

Reputation: 88777

You are directly using the Form class, you will need to create a instance of the form e.g.

klass = type('Form', (forms.Form,), fields)
form = klass()
return form

Upvotes: 1

Related Questions