Readonly for existing items only in Django admin inline

前端 未结 7 1294
长发绾君心
长发绾君心 2020-12-13 14:27

I have a tabular inline model in the Django admin. I need 1 of the fields to not be changeable after it has been created, but setting it as readonly (via readonly_fields) wh

7条回答
  •  执念已碎
    2020-12-13 14:58

    According to this post this issue has been reported as a bug in Ticket15602.

    A workaround would be to override the clean method of the inline model in forms.py and raise an error when an existing inline is changed:

    class NoteForm(forms.ModelForm):
        def clean(self):
            if self.has_changed() and self.initial:
                raise ValidationError(
                    'You cannot change this inline',
                    code='Forbidden'
                )
            return super().clean()
    
        class Meta(object):
            model = Note
            fields='__all__'
    

    The above gives a solution on the model level.

    To raise an error when a specific field is changed, the clean_ method can help. For example, if the field is a ForeignKey called category:

    class MyModelForm(forms.Form):
        pass  # Several lines of code here for the needs of the Model Form
    
    # The following form will be called from the admin inline class only
    class MyModelInlineForm(MyModelForm):
        def clean_category(self):
            category = self.cleaned_data.get('category', None)
            initial_value = getattr(
                self.fields.get('category', None), 
                'initial', 
                None
            )
            if all(
                (
                    self.has_changed(),
                    category.id != initial_value,
                )
            ):
                raise forms.ValidationError(
                    _('You cannot change this'),
                    code='Forbidden'
                )
            return category
    
    
        class Meta:
            # Copy here the Meta class of the parent model 
    

提交回复
热议问题