0

I have a json object like this:

    {  
 "Enzyme": {
        "order": 1,
        "required": "no",
        "help": "enzyme",
        "dataType": "CharField"   },   
"Date": {
        "order": 2,
        "required": "yes",
        "help": "date",
        "dataType": "DateField"   } 
}

And now I want to initialize a form something like this:

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for key,values in jsonObj.items():
            self.fields[key] = forms.values["dataType"]

I am not sure how can I do this, as taking this datatype from my json input. What should I write after forms. to initialize forms? Right now it's throwing an error module 'django.forms' has no attribute 'values'

Ankita Nand
  • 137
  • 1
  • 12
  • Does this answer your question? [Making a Django form class with a dynamic number of fields](https://stackoverflow.com/questions/5478432/making-a-django-form-class-with-a-dynamic-number-of-fields) – JPG Mar 18 '20 at 19:05
  • Thanks Arakkal! I looked into dynamic forms but nothing really fit my requirements. – Ankita Nand Mar 19 '20 at 02:50

1 Answers1

0

Answer should be: getattr(forms, values["dataType"])

Similar to this one: Accessing models by variable model name in django

This way helps me to create dynamic forms from a json stored in the database.

Ankita Nand
  • 137
  • 1
  • 12