Login

Copy/Paste form generation

Author:
dballanc
Posted:
November 6, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.