**How to:** {Actionable Phrase from Question} {Object from Question}
Purpose
- It takes a tuple or list containing the names of fields you want to exclude.
- The
exclude
attribute ofModelAdmin
is used to hide specific fields from the Django admin interface when editing or creating model instances.
How it Works
- Registration
When you register a model with the admin usingadmin.site.register(MyModel, MyModelAdmin)
, Django considers theexclude
attribute inMyModelAdmin
. - Field Listing
The admin interface uses theexclude
list to filter out the specified fields from the default set of fields for your model. - Hidden Fields
The excluded fields are no longer displayed in the admin forms for creating, editing, or viewing model instances.
Example
from django.contrib import admin
from .models import Book
class BookAdmin(admin.ModelAdmin):
exclude = ('slug',) # Exclude the 'slug' field from the admin interface
admin.site.register(Book, BookAdmin)
In this example, the slug
field will be hidden from the admin forms for creating, editing, and viewing Book
instances.
Important Points
exclude
is primarily for controlling the display of fields in the admin interface. It doesn't affect database access or manipulation.- Consider using
readonly_fields
to make fields read-only instead of hiding them completely, if appropriate. exclude
has higher precedence thanfields
inModelAdmin
. If you specify a field in bothexclude
andfields
, it will be excluded.
- Conditional logic
Use conditional logic within your admin templates to hide fields based on specific scenarios. - get_fields() method
Override this method in yourModelAdmin
class to dynamically determine which fields to exclude based on specific conditions.
Excluding Multiple Fields
class ProductAdmin(admin.ModelAdmin):
exclude = ('description', 'created_at') # Exclude 'description' and 'created_at' fields
Dynamic Exclusion with get_fields()
from django.contrib import admin
class ArticleAdmin(admin.ModelAdmin):
def get_fields(self, request, obj=None):
fields = super().get_fields(request, obj)
if obj: # Only exclude 'author' when editing existing articles
fields = [f for f in fields if f != 'author']
return fields
admin.site.register(Article, ArticleAdmin)
Using readonly_fields for Read-Only Fields
class OrderAdmin(admin.ModelAdmin):
exclude = ('created_at',) # Exclude 'created_at' but keep it read-only
readonly_fields = ('total_price',) # Make 'total_price' read-only
admin.site.register(Order, OrderAdmin)
Conditional Exclusion with Template Logic
(This example requires modifying your admin templates)
{% if request.user.is_superuser %}
{{ form.title }} {% endif %}
get_fields() method
- You can access information like the current user, the instance being edited (if any), and use them to control the displayed fields.
- This method allows you to dynamically determine which fields to include or exclude based on specific conditions.
- Override the
get_fields()
method in yourModelAdmin
class.
from django.contrib import admin
class ProductAdmin(admin.ModelAdmin):
def get_fields(self, request, obj=None):
fields = super().get_fields(request, obj) # Get default fields
if not request.user.is_staff: # Exclude 'wholesale_price' for non-staff users
fields = [f for f in fields if f != 'wholesale_price']
return fields
admin.site.register(Product, ProductAdmin)
Custom ModelForm
- Set the
form
attribute of yourModelAdmin
class to your custom form. - Define the
fields
orexclude
attributes in theMeta
class of your form to control which fields are included. - Create a custom
ModelForm
subclass for your model.
from django import forms
from .models import User
class UserForm(forms.ModelForm):
class Meta:
model = User
exclude = ('password',) # Exclude password field
class UserAdmin(admin.ModelAdmin):
form = UserForm
admin.site.register(User, UserAdmin)
Fieldsets
- This allows you to create a more organized layout for the admin interface without completely hiding fields.
- You can define which fields belong to each fieldset.
- Use
fieldsets
in yourModelAdmin
class to group related fields together.
class ArticleAdmin(admin.ModelAdmin):
fieldsets = (
('Basic Information', {
'fields': ('title', 'slug'),
}),
('Content', {
'fields': ('content',),
}),
)
admin.site.register(Article, ArticleAdmin)
Template Logic (Conditional Visibility)
- You can use Django template tags like
{% if %}
to conditionally display or hide fields based on various factors. - This approach involves modifying your admin templates.
{{ form.description }} {% if show_description %}
{{ form.description }}
{% endif %}
- Template Logic: Offers fine-grained control over field visibility based on custom conditions.
- Fieldsets: Great for organizing related fields and improving the admin interface layout.
- Custom ModelForm: Useful for global field control or specific logic within the form itself.
get_fields()
: Ideal for dynamic exclusion based on request context or object state.