django admin创建的时候的admin.py 中书写的案例

本文通过一个具体的案例展示了如何在Django的admin.py中自定义Employe模型的管理界面,包括设置list_display、search_fields、list_per_page、raw_id_fields、list_filter等属性,以及添加自定义操作按钮如test、make_copy,并详细配置了按钮的样式、类型和行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@admin.register(Employe)
class EmployeAdmin(ImportExportActionModelAdmin):
    resource_class = ProxyResource
    list_display = ('id', 'name', 'gender', 'phone', 'birthday', 'department', 'enable', 'create_time')
    # search_fields = ('name', 'enable', 'idCard', 'department')
    search_fields = ('name', 'department__name')
    list_per_page = 20
    raw_id_fields = ('department', 'title')
    list_filter = ('department', AgeListFilter, 'create_time')
    # list_filter = (AgeListFilter, 'department', 'create_time', 'birthday', 'time', 'enable', 'gender')

    list_display_links = ('name',)

    list_editable = ('department', 'phone', 'birthday', 'enable', 'gender')

    date_hierarchy = 'create_time'

    fieldsets = [(None, {'fields': ['name', 'gender', 'phone']}),
                 (u'其他信息', {
                     'classes': ('123',),
                     'fields': ['birthday', 'department', 'enable']})]

    @transaction.atomic
    def test(self, request, queryset):
        pass

    # 增加自定义按钮
    actions = [test, 'make_copy', 'custom_button']

    def custom_button(self, request, queryset):
        pass

    # 显示的文本,与django admin一致
    custom_button.short_description = '测试按钮'
    # icon,参考element-ui icon与https://fontawesome.com
    custom_button.icon = 'fas fa-audio-description'

    # 指定element-ui的按钮类型,参考https://element.eleme.cn/#/zh-CN/component/button
    custom_button.type = 'danger'

    # 给按钮追加自定义的颜色
    custom_button.style = 'color:black;'

    # 链接按钮,设置之后直接访问该链接
    # 3中打开方式
    # action_type 0=当前页内打开,1=新tab打开,2=浏览器tab打开
    # 设置了action_type,不设置url,页面内将报错

    custom_button.action_type = 1
    custom_button.action_url = 'https://www.baidu.com'

    def make_copy(self, request, queryset):
        ids = request.POST.getlist('_selected_action')
        for id in ids:
            employe = Employe.objects.get(id=id)

            Employe.objects.create(
                name=employe.name,
                idCard=employe.idCard,
                phone=employe.phone,
                birthday=employe.birthday,
                department_id=employe.department_id
            )

    make_copy.short_description = '复制员工'

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值