[Django]-Django ModelAdmin get_form() doesn't set fields attribute

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
👤ndpu

Leave a comment