Login

Copy/Paste form generation

Author:
dballanc
Posted:
November 6, 2007
Language:
Python
Version:
.96
Tags:
form copy generator paste
Score:
2 (after 2 ratings)

Generator to help make newforms classes a bit like inspectdb does for generating rough model code. This is a standalone script to go in your project directory with settings.py and called from the prompt. It looks up the model, and generates code to copy/paste into your app. Hopefully to make a building a custom form with a lot of fields a little easier. Every argument should be a model identifier of form appname.modelname.

Usage from the command line:

python form_gen myapp.MyModel myapp.MyOtherModel
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/python
import sys, os
import datetime
from django.core.management import setup_environ
import settings 
project_directory = setup_environ(settings)
project_name = os.path.basename(project_directory)
os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % project_name
from django.db import models

def textform_for_model(model_name):
    app,mdl = model_name.split('.')
    model = models.get_model(app,mdl)
    opts = model._meta
    field_list = []
    for f in opts.fields + opts.many_to_many:
        if not f.editable:
            continue
        formfield = f.formfield()
        if formfield:
            kw=[]
            for a in  ['queryset','maxlength','label','initial','help_text','required']:
                if hasattr(formfield,a):
                    attr = getattr(formfield,a)
                    if attr in [True,False,None]:
                        kw.append("%s=%s" % (a,attr))
                    elif a == 'queryset':
                        kw.append("%s=%s" %(a,"%s.objects.all()" % attr.model.__name__))
                    elif attr:
                        kw.append("%s='%s'" % (a,attr))
            f_text = "    %s = forms.%s(%s)" % (f.name,formfield.__class__.__name__ ,','.join(kw))
            field_list.append(f_text)
    return "class %sForm(forms.Form):\n" % model.__name__ + '\n'.join(field_list)

if __name__ == "__main__":
    cmdl = sys.argv
    for n in cmdl[1:]:
           print textform_for_model(n)
           print "\n"

More like this

  1. FixedCharField and related by andresj 6 years, 7 months ago
  2. MediaWiki Markup by zeeg 8 years, 3 months ago
  3. Regrouping admin models by sleytr 7 years, 5 months ago
  4. Clone model mixin by zakj 6 years, 6 months ago
  5. Make hyperlinks for labels of raw_id_fields (jQuery) by ramen 5 years, 6 months ago

Comments

Please login first before commenting.