Dimitris Kougioumtzis Blog About technology

Django dynamic form class

Category Django

Posted on Dec. 10, 2017



Django dynamic form class


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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

About

My name is Dimitris Kougioumtzis and i work as a Web developer at Rapidbounce Company

Elsewhere