JuniorKube.245
JuniorKube.245

Reputation: 81

In Django, how can make an inline field editable only if it is null or empty?

I currently have a tabular inline that has an end_date field for a model. I want the field to only be editable if it is empty or null, and read only otherwise.

Is there a way to achieve that?

Currently, I have it editable regardless, but I want the data that already exists to be read only. Here is the code:


class DeploymentInline(DecoratedTabularInline):
    model = Deployment
    readonly_fields = ['updated_at', 'updated_by', 'start_date', 'tool']
    fields = ['tool', 'updated_at', 'updated_by', 'start_date', 'end_date', ]

    def has_add_permission(self, request, obj):
        return False

I tried using get_readonly_field and checking the obj parameter, but it refers to the Project which is the admin.ModelAdmin the inline is in.

Upvotes: 0

Views: 219

Answers (1)

ruddra
ruddra

Reputation: 51988

You can add override the form of the InlineAdmin Form, like this:

class DeploymentAdminForm(ModelForm):
    class Meta:
        model = Deployment

    def __init__(self, instance=None, **kwargs):
        super().__init__(instance=instance, **kwargs)
        if instance and instance.end_date:
            self.fields['end_date'].disabled = True

class DeploymentInline(DecoratedTabularInline):
    form = DeploymentAdminForm

More information can be found in documentation.

Upvotes: 1

Related Questions