Django disable editing (but allow adding) in TabularInline view

前端 未结 4 2238
小鲜肉
小鲜肉 2021-02-19 23:40

I want to disable editing ALL objects within a particular TabularInline instance, while still allowing additions and while still allowing editing of the parent model.

I

4条回答
  •  伪装坚强ぢ
    2021-02-19 23:44

    You can try creating a separate inline class (see the InlineModelAdmin docs) that uses a custom ModelForm where you can customise the the clean method to throw an error when trying to update:

    from django.contrib import admin
    from django.core.exceptions import ValidationError
    from django.forms import ModelForm
    
    from myapp.models import Supervisee
    
    
    class SuperviseeModelForm(ModelForm):
        class Meta(object):
            model = Supervisee
            # other options ...
    
        def clean(self):
            if self.instance.pk:
                # instance already exists
                raise ValidationError('Update not allowed')
            # instance doesn't exist yet, continue
            return super(SuperviseeModelForm, self).clean()
    
    
    class SuperviseeInline(admin.TabularInline):
        model = Supervisee
        form = SuperviseeModelForm
    
    
    class SuperviseeAdmin(admin.ModelAdmin):
        inlines = [SuperviseeInline]
    

提交回复
热议问题