Generate Django admin file from model definition with regexes

Script to convert Django models.py to admin.py files automatically. When using Django every day i have to write a lot of code in the admin.py file to write the admin classes definitions and it can be automatized from models.py models definition, so i wrote this script. Enjoy!

Here is the full script i wrote

#!/usr/bin/python

import sys, re

file = open(sys.argv[1]).read()
classes = re.split(r'^class',file,flags=re.MULTILINE)

templ = """
class %sAdmin(admin.ModelAdmin):
    fieldsets = [
        ('',
            {'fields': ["%s"]}
         ),
    ]
    list_display = ["%s"]
    list_display_links = ["%s"]
    list_filter = [
        # "%s",
    ]
    readonly_fields = []
    list_editable = []
    search_fields = ["%s"]
    filter_horizontal = []
    inlines = []


admin.site.register(%s, %s)
"""

for c in classes:
    l = re.compile(r'([^\s\(]+)\(.+\):\n([\s\S]+)').findall(c)
    str = ""
    if len(l) > 0:
        class_name = l[0][0]
        class_content = l[0][1]
        fields = []
        fields_all = []
        fields_non_foreignkey = []
        for line in class_content.splitlines():
            m = re.compile(r'\s+([^\s]+)\s?=\s?(models\.|Content[^\(]+)([^\(]*)').findall(line)
            if len(m) > 0:
                # it's a model field
                if len(m[0]) == 3:
                    field_name = m[0][0]
                    field_type = m[0][2]
                    fields_all.append(field_name)
                    if field_type not in ["ForeignKey"]:
                        fields_non_foreignkey.append(field_name)
                    if field_type not in ["ManyToManyField","TextField"]:
                        fields.append(field_name)
                # it's a ContentType field
                if len(m[0]) == 2:
                    field_name = m[0][0]
                    fields_all.append(field_name)
                    fields.append(field_name)
                continue
            # non standard fields
            m = re.compile(r'\s+([^\s]+)\s?=\s?(RichTextField|GeopositionField)([^\(]*)').findall(line)
            if len(m) > 0:
                field_name = m[0][0]
                field_type = m[0][1]
                fields_all.append(field_name)
                if field_type not in ["RichTextField"]:
                    fields.append(field_name)
        print(templ % (
            class_name,
            '", "'.join(fields_all),
            '", "'.join(fields),
            '", "'.join(fields),
            ('",\n' + ' ' * 8 + '# "').join(fields_all),
            '", "'.join(fields_non_foreignkey),
            class_name,
            class_name + "Admin"))

The gist version

A test of execution:

from this models.py

it generates this admin.py file