1 | #!/usr/bin/env python
|
---|
2 | import os
|
---|
3 | import sys
|
---|
4 | from optparse import OptionParser
|
---|
5 |
|
---|
6 | INDENTCOUNT = 4
|
---|
7 | INDENTCHAR = ' '
|
---|
8 |
|
---|
9 | parser = OptionParser()
|
---|
10 | parser.add_option('-a', '--app', dest='app', help='The app which contains the model.')
|
---|
11 | parser.add_option('-m', '--model', dest='model', help='The model to produce the Form for.')
|
---|
12 | parser.add_option('-p', '--path', dest='path', help='The path to look for the files, directories separated by space.')
|
---|
13 | parser.add_option('-w', '--write', dest='file', help='The output file to append the form to, without this argument the output is printed.')
|
---|
14 |
|
---|
15 | options, args = parser.parse_args()
|
---|
16 |
|
---|
17 | if not(options.model and options.app):
|
---|
18 | parser.print_help()
|
---|
19 | sys.exit()
|
---|
20 |
|
---|
21 | if options.path:
|
---|
22 | sys.path += options.path.split()
|
---|
23 |
|
---|
24 | if options.file:
|
---|
25 | sys.stdout = file(options.file, 'a')
|
---|
26 |
|
---|
27 | try:
|
---|
28 | if 'DJANGO_SETTINGS_MODULE' in os.environ:
|
---|
29 | settings = __import__(os.environ['DJANGO_SETTINGS_MODULE'])
|
---|
30 | else:
|
---|
31 | import settings
|
---|
32 | except 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 |
|
---|
36 | project_directory = os.path.dirname(settings.__file__)
|
---|
37 | project_name = os.path.basename(project_directory)
|
---|
38 |
|
---|
39 | sys.path.append(os.path.join(project_directory, '..'))
|
---|
40 | project_module = __import__(project_name)
|
---|
41 | os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % project_name
|
---|
42 | from django.newforms import form_for_model
|
---|
43 |
|
---|
44 | models = __import__('%s.%s.models' % (project_name, options.app,), '', '', [options.model])
|
---|
45 | model = getattr(models, options.model)
|
---|
46 |
|
---|
47 | fields = model._meta.fields + model._meta.many_to_many
|
---|
48 |
|
---|
49 | print 'class %sForm(forms.Form):' % (options.model)
|
---|
50 | for 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 |
|
---|