Django admin - remove field if editing an object

后端 未结 2 1926
借酒劲吻你
借酒劲吻你 2021-01-05 09:48

I have a model which is accessible through the Django admin area, something like the following:

# model
class Foo(models.Model):
    field_a = models.CharFie         


        
2条回答
  •  情话喂你
    2021-01-05 10:25

    You can create a custom ModelForm for the admin to drop the field in the __init__

    class FooForm(forms.ModelForm):
        class Meta(object):
            model = Foo
    
        def __init__(self, *args, **kwargs):
            super(FooForm, self).__init__(*args, **kwargs)
            if self.instance and self.instance.pk:
                # Since the pk is set this is not a new instance
                del self.fields['field_b']
    
    class FooAdmin(admin.ModelAdmin):
        form = FooForm
    

    EDIT: Taking a hint from John's comment about making the field read-only, you could make this a hidden field and override the clean to ensure the value doesn't change.

    class FooForm(forms.ModelForm):
        class Meta(object):
            model = Foo
    
        def __init__(self, *args, **kwargs):
            super(FooForm, self).__init__(*args, **kwargs)
            if self.instance and self.instance.pk:
                # Since the pk is set this is not a new instance
                self.fields['field_b'].widget = forms.HiddenInput()
    
        def clean_field_b(self):
            if self.instance and self.instance.pk:
                return self.instance.field_b
            else:
                return self.cleaned_data['field_b']  
    

提交回复
热议问题