[Answered ]-Django Admin โ€“ Disable Update For FK Fields

2๐Ÿ‘

โœ…

You can override the get_form() method in the admin class to use a different form in the edit & create pages:

class ReadOnlyPkForm(ModelForm):
    class Meta:
        model = MyModel
        exclude = ('myothermodel',)



class MyModelAdmin(ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        if obj: # Object intstance, so we're in edit page
            # Override form, to use custom form 
            kwargs['form'] = ReadOnlyPkForm
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

The previous snippet would use the custom ReadOnlyPkForm form โ€” which excludes the field โ€” when you attempt to edit an instance. The standard form (i.e. all model fields) without exclusion would be used when you attempt to create a new instance. You could further tweak ReadOnlyPkForm through init if you wanted the field to appear as read-only (I just used exclude to make the sample easier).

Note admin classes also have change_view() and add_view() methods that you could also use to override the forms in edit / create pages , but in my experience they are for more complex modifications (e.g. the underyling template) not to mention these two methods can have quirky behavior due to caching issues.

๐Ÿ‘คuser4873081

0๐Ÿ‘

If I understand your question correctly would this work?

Disable link to edit object in django's admin (display list only)?

๐Ÿ‘คPaul

Leave a comment