Django dynamic form class

Django -- Posted on Dec. 10, 2017

Django dynamic form class

              
                from importlib import import_module


class DynamicForm:
    form_file_name = None

    def __init__(self, form_file_name=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        app_name = self.model._meta.app_label
        model_name = self.model.__name__
        if hasattr(self, 'form_file_name'):
            if self.form_file_name:
                self.form_file_name = self.form_file_name
            else:
                self.form_file_name = 'forms'
        app_module = import_module('{}.{}'.format(
            app_name, self.form_file_name))
        form = getattr(app_module, '{}Form'.format(model_name))
        self.form_class = form
                  
   
            

Related Posts