Django admin大改造:从入门到放弃,不,是到精通!
在Django中,我们可以通过扩展和自定义admin应用来实现丰富的管理界面。以下是一些扩展Django admin的示例代码:
- 自定义列表页的显示字段:
from django.contrib import admin
from myapp.models import MyModel
class MyModelAdmin(admin.ModelAdmin):
list_display = ('field1', 'field2', 'get_custom_field')
def get_custom_field(self, obj):
return obj.field1 + obj.field2
admin.site.register(MyModel, MyModelAdmin)
- 添加搜索功能:
class MyModelAdmin(admin.ModelAdmin):
search_fields = ('field1', 'field2')
- 自定义编辑表单:
from django import forms
from django.contrib import admin
from myapp.models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
widgets = {
'field1': forms.TextInput(attrs={'class': 'my-class'}),
}
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
admin.site.register(MyModel, MyModelAdmin)
- 重写保存方法:
class MyModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
# 在保存前可以进行一些操作
super().save_model(request, obj, form, change)
admin.site.register(MyModel, MyModelAdmin)
- 添加过滤器:
class MyModelAdmin(admin.ModelAdmin):
list_filter = ('field1',)
admin.site.register(MyModel, MyModelAdmin)
这些示例展示了如何通过扩展Django admin的ModelAdmin类来自定义Django admin界面的不同方面。开发者可以根据自己的需求进一步扩展和自定义admin界面。
评论已关闭