3

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?

1
  • Then what's the main thing that get_form() should do? Also, if that's the case, how can I access fields on a form in a ModelAdmin class?
    – linkyndy
    Mar 18, 2014 at 14:43

1 Answer 1

3

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
3
  • Then how do I intercept form creation in a ModelAdmin so that I can alter its fields afterwards?
    – linkyndy
    Mar 18, 2014 at 14:51
  • @AndreiHorak form instantiates in add_view and change_view ModelAdmin methods, check them
    – ndpu
    Mar 18, 2014 at 15:03
  • 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.
    – linkyndy
    Mar 19, 2014 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.