Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ModelAdmin get_form() doesn't set fields attribute

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?

like image 622
linkyndy Avatar asked Dec 30 '25 14:12

linkyndy


1 Answers

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
like image 135
ndpu Avatar answered Jan 02 '26 08:01

ndpu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!