views:

89

answers:

1

I have a Django model:

class Customer(models.Model):
  first_name=models.CharField(max_length=20,null=True, blank=True)
  last_name=models.CharField(max_length=25,null=True, blank=True)
  address=models.CharField(max_length=60,null=True, blank=True)
  address2=models.CharField(max_length=60,null=True, blank=True)
  city=models.CharField(max_length=40,null=True, blank=True)
  state=models.CharField(max_length=2,null=True, blank=True)

From there, I created a ModelForm:

class CustomerForm(forms.ModelForm):
  class Meta:
    model=Customer

I'd like to be able to show pieces of the form in my template corresponding to specific information the users can change. For example, if I want to let the customers change their name, I'd like to be able to show a form that only has the fields 'first_name' and 'last_name'.

One way to do this would be to create a ModelForm for each of the various field snippets... for the name example, it would look something like:

class CustomerFormName(forms.ModelForm):
  class Meta:
    model=Customer
    fields=('first_name','last_name')

This seems pretty inelegant, and inflexible. What I'd like to do is be able to specify the fields at runtime, so when I pass the dictionary from the view to the template, I can just set which fields I'd like to show. How can I set it up so that I set the fields for a form at runtime? I'd ideally like the final dictionary passed to look something like this:

{'name_change_form':CustomerFormName(<form with only first_name and last_name>), 'address_change_form':CustomerFormName(<form with only address fields>)}

Then, I know that whenever I output name_change_form.as_p, it'll have exactly the form fields that I'm looking for.

Thoughts? Also feel free to recommend a better way to do it.

A: 
from django.forms import ModelForm
from wherever import Customer
def formClassFactory(model,fields):
  ff = fields
  mm = model
  class formClass(ModelForm):
    class Meta:
      model  = mm
      fields = ff
  return formClass
form_class = formClassFactory( ('first_name','last_name') )
eruciform