Pedro García
Pedro García

Reputation: 53

Modify individual objects on change list django admin

class WidgetManagerAdmin(FilterSiteAdmin, OrderedModelAdmin):
      list_display = ('title', 'position', 'is_published', 'order', 'reorder',)
      list_editable = ('position', 'is_published',)
      ordering = ('position','order',)

On this modelAdmin 'position' is an editable field represented by a select

I want to dynamically modify this select for the individual object. So i can individually make this field read_only when i require, and also modify the number of options in the select.

Thanks

Upvotes: 0

Views: 411

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

One way to do this is to set the field as readonly if it has the criteria you're looking for by using a custom form class for your admin class.

Example:

class YourClassAdminForm(forms.ModelForm):
    class Meta:
        model = YourModel

    def __init__(self, *args, **kwargs):
        super(YourClassAdminForm, self).__init__(*args, **kwargs)

        # Check for your criteria to be `readonly`
        if self.instance.whatever:
            style = 'border:none;background-color:transparent;color:#666;cursor:default;'
            self.fields['position].widget_attrs={'readonly': True, 'style': style}

You can also modify the choices within the same if statement. Django admin doesn't provide styling for readonly fields within a change list, which is why I'm adding some inline CSS for the widget.

Hope that helps you out.

Upvotes: 1

Related Questions