Login

auto generate admin.py

Author:
hank
Posted:
August 30, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

When you switch you django project from 0.9.6 to 1.0, you can use this script to generate admin.py automatically.

You need copy cvt.py to the parent directory of your project(where your project lies) and type "python cvt.py <project> <app>". The admin.py will generated in the <project>/<app>(where it should be!).

Enjoy this small work!

 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
37
38
39
40
41
42
#-----------------------------------------------------------------------------
# Name:        cvt.py
# Purpose:     auto generate django 1.0 admin.py from 0.9.6 models.py
#
# Author:      Hank Hu<[email protected]>
#
# Created:     2008/08/30
# Copyright:   (c) 2006
# Licence:     Public
#-----------------------------------------------------------------------------
import sys
assert len(sys.argv) == 3, "usage: cvt prjname appname"
prjname, appname = sys.argv[1:]

import os
os.environ['DJANGO_SETTINGS_MODULE'] = prjname + '.settings'

exec "from %s.%s import models" % (prjname,appname)

fp = open("%s/%s/admin.py" % (prjname,appname), "w")

print >> fp,  '''#coding: utf-8
from django.contrib import admin
from %s.%s.models import *
''' % (prjname,appname)

for name, klazz in models.__dict__.items():
    if isinstance(klazz, type) and issubclass(klazz, models.models.Model):
        #print name, klazz
        if hasattr(klazz, 'Admin'):
            print >> fp,  'class %sAdmin(admin.ModelAdmin):' % name
            #print dir(klazz.Admin)
            attrs = [(k, v) for k, v in klazz.Admin.__dict__.items() if k[0] != '_']
            if len(attrs):
                for k, v in attrs:
                    if k=='fields':
                        k = 'fieldsets'
                    print >> fp, "\t%s=%s" % (k, repr(v).encode('utf-8'))
            else:
                print >> fp, "\tpass"
            print >> fp, "admin.site.register(%s, %sAdmin)" % (name, name)
            print >> fp

More like this

  1. New Snippet! by Antoliny0919 4 days, 21 hours ago
  2. Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 3 weeks ago
  3. get_object_or_none by azwdevops 6 months, 2 weeks ago
  4. Mask sensitive data from logger by agusmakmun 8 months, 1 week ago
  5. Template tag - list punctuation for a list of items by shapiromatron 1 year, 10 months ago

Comments

twinsant (on July 31, 2009):

good work. thank you!

#

Please login first before commenting.