class Book(models.Model): title = models.CharField(..., null=True) type = models.CharField(...) author = models.CharField(...)
I have a simple class in models.py. In admin I would like to hide title of the book (in book details form) when type of the saved book is 1. How do this in a simplest way?
You would have to add blank=True as well in field definition. If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True.
Take a look at the Model Meta in the django documentation. Within a Model you can add class Meta this allows additional options for your model which handles things like singular and plural naming. Show activity on this post. inside model.py or inside your customized model file add class meta within a Model Class.
One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.
For Django > 1.8 one can directly set the fields to be excluded in admin:
class PostCodesAdmin(admin.ModelAdmin): exclude = ('pcname',)
Hidden fields are directly defined in Django's ORM by setting the Field attribute: editable = False
e.g.
class PostCodes(models.Model): gisid = models.IntegerField(primary_key=True) pcname = models.CharField(max_length=32, db_index=True, editable=False) ...
However, setting or changing the model's fields directly may not always be possible or advantegous. In principle the following admin.py
setup could work, but won't since exclude is an InlineModelAdmin option.
class PostCodesAdmin(admin.ModelAdmin): exclude = ('pcname',) ....
A solution working at least in Django 1.4 (and likely later version numbers) is:
class PostCodesAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(PostCodesAdmin, self).get_form(request, obj, **kwargs) del form.base_fields['enable_comments'] return form
For the admin list-view of the items, it suffices to simply leave out fields not required: e.g.
class PostCodesAdmin(admin.ModelAdmin): list_display = ('id', 'gisid', 'title', )
You are to create admin.py in your module (probably book)
class BookAdmin(admin.ModelAdmin): list_display = ("pk", "get_title_or_nothing")
In Book class:
class Book: ... def get_title_or_nothing(self): if self.type == WEIRD_TYPE: return "" return self.title
UPDATED:
class BookAdmin(admin.ModelAdmin): list_display = ("pk", "get_title_or_nothing") def get_form(self, request, obj=None, **kwargs): if obj.type == "1": self.exclude = ("title", ) form = super(BookAdmin, self).get_form(request, obj, **kwargs) return form
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With