Hello all,

I am trying to create a ModelForm subclass to customize the admin
interface for one of my models.  In particular, I am attempting to add
a field to the ModelForm dynamically in its __init__ method (per
advice found here: http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/).
I would like to be able to use this ModelForm subclass for custom
validation in the admin interface.

The trouble is that the dynamically-added field doesn't appear in the
admin interface.  If I instantiate the ModelForm subclass directly,
and call as_p() or similar, the input tag, etc. for the dynamically-
added field appears in the HTML form that is output; but if I assign
the ModelForm subclass to the "form" attribute in the model's
ModelAdmin class, I don't see the dynamically-added field in the admin
interface.  Example code below.

My question is:  is there something special about the way the admin
interface instantiates and/or displays ModelForms that would prevent
me from adding fields dynamically this way?  Do I need to do anything
else (e.g. override an admin template?) to see HTML inputs for these
fields in the admin?

Thanks for any and all help!

Best,
Richard

# hopefully-illustrative example code:

class Experiment(models.Model):
    name = models.CharField(max_length=50)
    # ...

class ExperimentForm(forms.ModelForm):
    class Meta:
        model = Experiment

   def __init__(self, *args, **kwargs):
        super(ExperimentForm, self).__init__(*args, **kwargs)
        # I add another field dynamically here:
        self.fields['email'] = forms.EmailField()

# If I call ExperimentForm().as_p(), I will see an HTML form with an
input for the "email" field...

class ExperimentAdmin(admin.ModelAdmin):
    form = ExperimentForm

admin.site.register(Experiment, ExperimentAdmin)

# ...but I see no such field in the HTML form for adding or changing
an Experiment
# in the admin interface
--~--~---------~--~----~------------~-------~--~----~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to