2

We could directly create a simple form by inheriting forms.Form. However, I want forms to be dynamically created based on the key-value specified by the admin. Consider, user provides a map as :

[
  {
    "key": "name",
    "value": "CharField"
  },
  {
    "key": "url",
    "value": "URLField"
  }
]

Based on the map given above how can I create a form which is equivalent to the class based form creation below:

from django import forms
class CommentForm(forms.Form):
    name = forms.CharField(label='name')
    url = forms.URLField(label='url')

My current approach might be to iterate across each key-value pair and make a HTML form manually. Is it possible to create dynamic forms in django without having to write a class definition?

2
  • Where do you get the extra-attributes (label, choices, etc.) from? Commented Jan 31, 2017 at 21:22
  • For now, we could assume its a value of key. However, I would add metadata based on the map. Commented Jan 31, 2017 at 21:23

1 Answer 1

1

Yes, you can do this in the init function of the form.

Pass in the mapping array as an extra keyword argument when creating the form, then pop it from the kwargs before calling the init method from super.

You can then use this to dynamically add fields to the form.

class CommentForm(forms.Form):

    def __init__(self , *args, **kwargs):
        field_mapping_array = kwargs.pop('field_mapping_array') 
        super(CommentFrom, self).__init__(*args, **kwargs)        

        for field_type in field_mapping_array:
            field_name = field_type['key'] # make sure keys are unique
            if field_type[value] == "CharField":
                self.fields[field_name] = form.CharField(...extra args here)     
             elif field_type['value'] == 'UrlField' :
                self.fields[field_name] = form.UrlField(...extra args here)  
             elif .... map other field types here....

When creating the form pass the field_mapping_array into the form class.

field_mapping = [
    {
        "key": "name",
        "value": "CharField"
     },
     {
       "key": "url",
       "value": "URLField"
     }
]
comment_form = CommentForm(field_mapping_array=field_mapping)   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.