Django admin - deleting a field when editing an object

I have a model available through the Django admin area, something like the following:

# model class Foo(models.Model): field_a = models.CharField(max_length=100) field_b = models.CharField(max_length=100) # admin.py class FooAdmin(admin.ModelAdmin): pass 

Let's say that I want to show field_a and field_b if the user is adding an object, but only field_a if the user is editing the object. Is there an easy way to do this, possibly using the fields attribute?

If this happens, I can hack a JavaScript solution, but it’s not so!

+4
source share
2 answers

You can create a custom ModelForm for the administrator to remove the field in __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: By emphasizing John’s comment about creating a read-only field, you can make it a hidden field and override purity to ensure that the value does not 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'] 
+5
source

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: eliminate the field only in the form changes

0
source

Source: https://habr.com/ru/post/1310254/


All Articles