Django

Code

ScaffoldScript: scaffold_mr2.py

File scaffold_mr2.py, 2.3 kB (added by nate-django@refried.org, 2 years ago)

Fixed a syntax error in the magic-removal version.

Line 
1 #!/usr/bin/python
2
3 from optparse import OptionParser
4 import sys
5 import os
6
7 try:
8     import settings
9 except ImportError:
10     print "Settings file not found.  Place this file in the same place as manage.py"
11     sys.exit()
12
13 project_directory = os.path.dirname(settings.__file__)
14 project_name = os.path.basename(project_directory)
15 sys.path.append(os.path.join(project_directory, '..'))
16 project_module = __import__(project_name, '', '', [''])
17 sys.path.pop()
18 os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % project_name
19
20 from django.db import models
21 from django.template import Context, Template
22
23 p = OptionParser()
24
25 p.add_option("-a", "--app", dest="app", help="The app which contains the model")
26 p.add_option("-m", "--model", dest="model", help="The model to produce the form for")
27
28 options, args = p.parse_args()
29
30 if not (options.model and options.app):
31     p.print_help()
32     sys.exit()
33
34 m = __import__("%s.%s.models" % (project_name, options.app,), '', '', [options.model])
35
36 a = getattr(m, options.model)
37
38 def image_field_html(name):
39     return '''\
40         {{ form.NAME_file }} \
41         {{ form.NAME }}
42         {% if form.NAME.errors %}
43         *** {{ form.NAME.errors|join:", " }}
44         {% endif %}'''.replace('NAME', name)
45
46 def field_html(name):
47     return '''\
48     {{ form.NAME }}
49     {% if form.NAME.errors %}
50       *** {{ form.NAME.errors|join:", " }}
51     {% endif %}'''.replace('NAME', name)
52
53
54 def labeled_field_html(field):
55     if isinstance(field, models.DateTimeField):
56         rows = [field_html(field.name + '_' + suffix)
57                 for suffix in 'date', 'time']
58     elif isinstance(field, models.ImageField):
59         rows = [image_field_html(field.name)]
60     else:
61         rows = [field_html(field.name)]
62     return '''\
63   <p>
64     <label for="id_%s">%s:</label>
65 %s
66   </p>''' % (field.name, field.verbose_name or field.name, '\n'.join(rows))
67
68
69 #print '<form method="POST" action=".">'
70 #print '\n'.join(labeled_field_html(f) for f in a._meta.fields if f.name !='id')
71 #print '  <input type="submit" value="submit" />'
72 #print '</form>'
73
74 template = Template(
75 """<form method="POST" action=".">
76 {{ formfields }}
77 <input type="submit" value="submit" />
78 </form>
79 """)
80
81 context = Context({'formfields': '\n'.join([labeled_field_html(f) for f in a._meta.fields + a._meta.many_to_many if f.name !='id'])})
82 print template.render(context)