views:

88

answers:

3
def SiteAdminForm(model_cls, *args, **kwargs):
    class MerchantAdminForm(forms.ModelForm):
        class Meta:
            exclude = ('external_links', 'published', 'logo','image_zip_file',)
            model = model_cls

        def __init__(self, *args, **kwargs):
            super(MerchantAdminForm, self).__init__(*args, **kwargs)

    return MerchantAdminForm()

# In use...
merchant_form = SiteAdminForm(merchant.__class__, instance=merchant)

No matter what is passed into model_cls, model is always ignored.

Meta.exclude is set properly, how can I dynamically update the Meta.model?

A: 

That's because your merchant.__class__ is also django.db.models.base.ModelBase. If you just try to print merchant, then you will get proper class path (I get app.models.TestModel), but class is BaseModel.

I believe that's because of metaclasses use. Probably the metaclass sets the class of an object to ModelBase. Django extensively use this python feature and this may cause some strange behaviour (which means strange for people, that don't exactly get it, like me ;-), not that it doesn't work). I'll try to take a look at django code - you should too :-)

Anyway, you get what you want inside your form and it should work just fine :-)

DAMMIT

Of course I know, why this is happening. You are asking for the class of a class, you know. Inside form.Meta.model is a class, the one you have passed into the form. This is why you get ModelBase - you get the metaclass.

It's worth reading about metaclasses, because they are cool. Though they are a bit complicated too ;-) Here you can read about them.

gruszczy
A: 

Try to use like this:

merchant_form = SiteAdminForm(merchant.model, instance=merchant)

One suggestion is to use the Python shell (in django case, ./manage.py shell) to inspect attributes and methods of an object with the built-in dir() function.

Igor Sobreira
A: 

I'm an idiot, slept on it, looked at it again and figured it out almost immediately!!!!

'return MerchantAdminForm()' should have been: 'return MerchantAdminForm(*args, **kwargs)'

Mike