Django admin - remove field if editing an object

后端 未结 2 1927
借酒劲吻你
借酒劲吻你 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']  
    
    0 讨论(0)
  • 2021-01-05 10:49

    You can also do the following

    class FooAdmin(admin.ModelAdmin)
        def change_view(self, request, object_id, extra_context=None):       
            self.exclude = ('field_b', )
            return super(SubSectionAdmin, self).change_view(request, object_id, extra_context)
    

    Taken from here Django admin: exclude field on change form only

    0 讨论(0)
提交回复
热议问题