aldesabido
aldesabido

Reputation: 1288

Django: how to convert string into form?

How can I convert string into Form?

in model you can just use this line.

model = apps.get_model(app_label='app_label', model_name='str_model')

I have 3 forms namely:

and would like to do this.

type = "customer"
form = "Fund_"+type #that would make "Fund_customer"
form = apps.get_form(form) #I wonder if there's a function like this.

I just dont want to do if condition to achieve this.

Upvotes: 2

Views: 924

Answers (1)

Alasdair
Alasdair

Reputation: 308799

Django doesn't have a registry of form classes like it does for models.

The simplest solution is to make a dictionary with forms keyed by name

forms = {
    'customer': Fund_customer,
    'employee': Fund_employee,
    'supplier': Fund_supplier,
}

Then do a dictionary lookup to get the form class.

form_class = forms[form_type]

You need to remember to update the dictionary when you add a new form, but the advantage of this solution is that it is a lot simpler than creating a registry of form classes.

If all your forms are in the same forms.py module, you could try defining a function that uses getattr.

from myapp import forms

def get_form_class(form_type):
    class_name = 'Fund_%s' % form_type
    # third argument means it returns None by default instead of raising AttributeError
    return getattr(forms, class_name, None) 

Upvotes: 5

Related Questions