FormGenScript: form_generator.py

File form_generator.py, 2.1 KB (added by Rick@…, 17 years ago)

Improved version of the form generating script, includes verbose_name, help_text, required and allows appending to files.

Line 
1#!/usr/bin/env python
2import os
3import sys
4from optparse import OptionParser
5
6INDENTCOUNT = 4
7INDENTCHAR = ' '
8
9parser = OptionParser()
10parser.add_option('-a', '--app', dest='app', help='The app which contains the model.')
11parser.add_option('-m', '--model', dest='model', help='The model to produce the Form for.')
12parser.add_option('-p', '--path', dest='path', help='The path to look for the files, directories separated by space.')
13parser.add_option('-w', '--write', dest='file', help='The output file to append the form to, without this argument the output is printed.')
14
15options, args = parser.parse_args()
16
17if not(options.model and options.app):
18 parser.print_help()
19 sys.exit()
20
21if options.path:
22 sys.path += options.path.split()
23
24if options.file:
25 sys.stdout = file(options.file, 'a')
26
27try:
28 if 'DJANGO_SETTINGS_MODULE' in os.environ:
29 settings = __import__(os.environ['DJANGO_SETTINGS_MODULE'])
30 else:
31 import settings
32except ImportError:
33 print 'Settings file not found. Place this file in the same dir as manage.py or use the path argument.'
34 sys.exit()
35
36project_directory = os.path.dirname(settings.__file__)
37project_name = os.path.basename(project_directory)
38
39sys.path.append(os.path.join(project_directory, '..'))
40project_module = __import__(project_name)
41os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % project_name
42from django.newforms import form_for_model
43
44models = __import__('%s.%s.models' % (project_name, options.app,), '', '', [options.model])
45model = getattr(models, options.model)
46
47fields = model._meta.fields + model._meta.many_to_many
48
49print 'class %sForm(forms.Form):' % (options.model)
50for field in fields:
51 formfield = field.formfield()
52 if formfield:
53 fieldtype = str(formfield).split()[0].split('.')[-1]
54 arguments = {}
55 arguments['verbose_name'] = '\'%s\'' % field.verbose_name
56 arguments['help_text'] = '\'%s\'' % field.help_text
57 arguments['required'] = not field.blank
58
59 print '%s%s = forms.%s(%s)' % (INDENTCOUNT * INDENTCHAR, field.name, fieldtype, ', '.join(['%s=%s' % (k, v) for k, v in arguments.iteritems()]))
60
Back to Top