关于python:获取Django应用程序中的所有表单对象

Get all form objects in a Django application

我想做的是:

  • 检索从form a.form继承的所有Django应用程序中的所有对象的列表
  • 查找表单上定义的所有字符域
  • 验证每个字段是否都指定了最大长度kwarg
  • 我的目标是,如果系统中存在未指定最大长度的表单,则编写一个单元测试以失败。

    我该怎么做?


    我找到了一种使用反射样式代码来检索从模型继承的所有对象的方法。Form类,请参见下面的测试:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    class TestAllFormsMeetBasicBoundaryTests(TestCase):
        def all_subclasses(self, cls):
            return cls.__subclasses__() + [g for s in cls.__subclasses__()
                                       for g in self.all_subclasses(s)]

        # this is teh awesome-sause! dynamically finding objects in the project FTW!
        def test_all_char_fields_contain_max_length_value(self):
            from django.apps import apps
            import django.forms
            import importlib
            log.info('loading all forms modules from apps')
            at_least_one_module_found = False
            for app_name in settings.PROJECT_APPS: #this is a list of in project apps
                app = apps.get_app_config(app_name)
                try:
                    importlib.import_module('{0}.forms'.format(app.label))
                    log.info('forms loaded from {0}'.format(app.label))
                    at_least_one_module_found = True
                except ImportError as e:
                    pass
            self.assertTrue(at_least_one_module_found, 'No forms modules were found in any of the apps. this should never be true!')
            all_forms = self.all_subclasses(django.forms.Form)

            messages = []
            for form in all_forms:
                for key in form.declared_fields.keys():
                    field = form.declared_fields[key]
                    if isinstance(field, django.forms.CharField) and form.__module__.partition('.')[0] in settings.PROJECT_APPS and field.max_length is None:
                        messages.append('{0}.{1}.{2} is missing a max_length value.'.format(form.__module__, form.__name__, key))
                pass

            self.assertEquals(0, len(messages),
                              'CharFields must always have a max_length attribute specified. please correct the following:
    --{0}'

                              .format('
    --'
    .join(messages)))