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