On 2007-02-10 18:22:53 -0700, "johnny" <[EMAIL PROTECTED]> said:

> 
> I have to include some fields from 3 different models. How do you
> create a selection field, for selecting a category data, in category
> model, using newforms?
> 
> Thank You in advance.
> 
> 
> 
The way I managed to pull this off was to use a custom form class.

class ModelInstanceForm(forms.Form):
        def __init__(self, instance, data=None):
                if data == None:
                        data = {}
                        for k in self.base_fields.keys():
                                data['%d-%s' % (instance.id, k)] = 
getattr(instance, k)
                self.instance = instance
                super(ModelInstanceForm, self).__init__(data, 
prefix=instance.id)
        
        def save(self):
                clean_data = self.clean_data
                for k in self.base_fields.keys():
                        setattr(self.instance, k, clean_data[k])
                self.instance.save()

Then you override this class with a regular form class that defines the 
fields from the model you passed in.

class ProductForm(ModelInstanceForm):
        display_sort = forms.IntegerField()
        sku = forms.CharField(max_length=255)
        name = forms.CharField(max_length=255)
        is_stocked = forms.BooleanField(required=False)

So now your form object accepts an instance of a model and you can pick 
and choose which ones you want to use.  You can have multiple forms for 
each instance.  My ModelInstanceForm uses a prefix since I wrote this 
code to allow a form with data in one model and a foriegn key form like 
listing the products that belong to a product page.  So this may not 
work for you out of the box, but you can form an idea around it.

-- 
Brian Rosner
http://www.brosner.com/blog



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to