Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script to convert Django models.py to admin.py files automatically. https://www.robbiecode.com/generate-django-admin-file-from-model-definition-with-regexes/
#!/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"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.