FormGenScript: formGen.py

File formGen.py, 1.3 KB (added by Lllama, 18 years ago)

Initial upload

Line 
1from optparse import OptionParser
2import sys
3import os
4
5try:
6 import settings
7except ImportError:
8 print "Settings file not found. Place this file in the same dir as manage.py"
9 sys.exit()
10
11project_directory = os.path.dirname(settings.__file__)
12project_name = os.path.basename(project_directory)
13sys.path.append(os.path.join(project_directory, ".."))
14project_module = __import__(project_name, '', '', [''])
15sys.path.pop()
16os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % project_name
17
18from django.newforms import form_for_model
19
20p = OptionParser()
21
22p.add_option("-a", "--app", dest="app", help="The app which contains the model")
23p.add_option("-m", "--model", dest="model", help="The model to produce the Form for")
24
25options, args = p.parse_args()
26
27if not(options.model and options.app):
28 p.print_help()
29 sys.exit()
30
31m = __import__("%s.%s.models" % (project_name, options.app,), '', '', [options.model])
32
33a = getattr(m, options.model)
34
35fields = a._meta.fields + a._meta.many_to_many
36
37print "class %sForm(forms.Form):" % (options.model)
38for f in fields:
39 formfield = f.formfield()
40 if formfield:
41 fieldtype = formfield.__str__().split(".")[3].split(" ")[0]
42 print " %s = forms.%s()" % (formfield.label.lower().replace(" ","_"), fieldtype)
Back to Top