Django

Code

ManipulatorScript: manipulator.3.py

File manipulator.3.py, 3.0 kB (added by Lllama, 3 years ago)

Added a save method

Line 
1 #!/usr/bin/env 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.core import meta
21 from django.core.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 p.add_option("-n", "--name", dest="name", help="The name of the custom manipulator")
28
29 options, args = p.parse_args()
30
31 if not (options.model and options.app):
32     p.print_help()
33     sys.exit()
34
35 if not options.name:
36     options.name = "%s%s" % (options.app, options.model)
37
38 m = __import__("django.models.%s" % (options.app,), '', '', [options.model])
39
40 a = getattr(m, options.model)
41
42 def field_text(field):
43     d = field.__dict__
44     args = dict([(f, isinstance(d[f], str) and "'%s'" % d[f] or d[f]) for f in d if f not in ['db_index', 'primary_key', 'rel', 'core', 'creation_counter',
45     'editable', 'name', 'default', 'column', 'attname', 'auto_now_add', 'help_text', 'auto_now']])
46     if args['blank'] is True or args['null'] is True:
47         args['is_required'] = False
48     else:
49         args['is_required'] = True
50     try:
51         del(args['blank'])
52         del(args['null'])
53     except KeyError:
54         pass
55     try:
56         args['validator_list'] = ['%s' % v.__name__ for v in args['validator_list']]
57     except KeyError:
58         pass
59     extra_args = ["%s=%s" % (s, args[s]) for s in args if args[s] not in [None, '', False, []]]
60     if extra_args:
61         return '''\
62             formfields.%s(field_name='%s', %s)\
63         ''' % (field.__class__.__name__, field.name, ', '.join(extra_args))
64     else:
65         return '''formfields.%s(field_name='%s')\
66         ''' % (field.__class__.__name__, field.name)
67
68 def value_text(field):
69     return """\
70             %s=new_data['%s']""" % (field.name, field.name)
71
72 def m2m_text(field):
73     return """temp.set_%s(newdata['%s'])""" % (field.name, field.name)
74
75 template = Template(
76 """class {{ name }}Manipulator(formfields.Manipulator):
77     def __init__(self, pk=None):
78         self.fields = (
79 {{ fields }}
80         )
81
82     def save(self, new_data):
83         temp = {{ model }}(
84 {{ values }}
85         )
86         {{ m2m }}
87         temp.save()
88         return temp
89         """)
90
91 context = Context({'fields': '\n'.join(field_text(f) for f in a._meta.fields + a._meta.many_to_many if f.name !='id'), 'name': options.name,
92                 'model': options.model, 'values': ',\n'.join(value_text(f) for f in a._meta.fields if f.name != 'id'),
93                 'm2m': '\n'.join(m2m_text(f) for f in a._meta.many_to_many)})
94 print template.render(context)