2

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:

  • Fund_customer
  • Fund_employee
  • Fund_supplier

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.

2
  • Do you mean you want to make a form from a model object or just turn the string "cheese" into a form?... Commented Feb 9, 2017 at 16:11
  • Yes. I updated my header. sorry for the mistake Commented Feb 9, 2017 at 16:19

1 Answer 1

5

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks bro. Gonna use this instead.
There is the modelform_factory function but I wasn't sure if this is what the OP was looking for
@sayse Yes, if the model forms are simple enough then you might be able to use modelform_factory instead of defining the form classes. Be careful to validate the model name though!

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.