[Django]-Is it possible to disable a field in Django admin?

1👍

You can do this by overriding the get_form method in you ModelAdmin:

class StepModelAdmin(admin.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        form = super(StepModelAdmin, self).get_form(request, obj, **kwargs)

        if Step.objects.count() > 1:

            # this will hide the null option for the parent field
            form.base_fields['parent'].empty_label = None

        return form

6👍

I am not exactly getting what you want to do but yahh you can exclude field or declare particular field as read only:

class StepOver(admin.TabularInline):
       model = Step
       exclude = ['parent']
       readonly_fields=('parent', )
👤py-D

1👍

You can override the save method in the models

Ex:

def save(self):
    if Step.objects.count() > 1:
        if not self.parent:
            print("Error")
        else:
            super(Step, self).save()
👤Rakesh

1👍

I would like to thank @Peter for his answer, I just adapted the code with my problem so I give it if anyone is in need !!

class StepAdmin(admin.ModelAdmin):

      def get_form(self, request, obj=None, **kwargs):
           form = super(StepAdmin, self).get_form(request, obj, **kwargs)

           if Step.objects.filter(parent__isnull=True).count() > 1:

                # this will hide the null option for the parent field
                form.base_fields['parent'].empty_label = None

           return form
👤Beno

Leave a comment