I've overriden get_form() in my ModelAdmin class:
def get_form(self, request, obj=None, **kwargs):
form = super(ModelAdmin, self).get_form(request, obj, **kwargs)
Now, if I add this line:
print form.fields
I get an:
AttributeError: type object 'FilerImageForm' has no attribute 'fields'
Why is this happening? Should the call to the super get_form() set the fields attribute on the form? If I am mistaken, how can I access fields on a form in a ModelAdmin class?
get_form returns class not instance and fields attribute is instance attribute. So, you have to instantiate form before accessing fields.
Definition from django/contrib/admin/options.py:
def get_form(self, request, obj=None, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
update:
I need to intercept form field creation, not the view. I need to change a field's value, not mess with a template's context. I don't think add_view() is the appropriate place for this.
I think you can do it by overriding formfield_for_dbfield method:
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.
If kwargs are given, they're passed to the form Field's constructor.
"""
formfield = super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == "field_you_are_looking_for":
# change formfield somehow here
# (or above, by passing modified kwargs in 'super' call)
return formfield
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With