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. Template tag - list punctuation for a list of items by shapiromatron 1 month, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 month, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 8 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 1 week ago
  5. Help text hyperlinks by sa2812 10 months, 1 week ago

Comments

twinsant (on July 31, 2009):

good work. thank you!

#

Please login first before commenting.