Home > database >  how to add a custom button that can used clicked event in django admin.py
how to add a custom button that can used clicked event in django admin.py

Time:07-03

I have a model which named Record, the model have the source code info. Now, I want add a button in the admin site. Current django admin.py code like:

@admin.register(Record)
class ControlRecord(admin.ModelAdmin):
    list_display = ["file_path", "go_to_src_code", "func_info", "line"]
    search_fields = ['file_path', 'func_info']
    list_filter = ['severity', 'is_misinformation']
    actions = [jump_to_src_code]

    def go_to_src_code(self, obj):
        return format_html(
            '<button onclick= "" >Go</button>'
        )

    go_to_src_code.short_description = "GoToSrcCode"

I want to specify the specified method after clicking the button, what should i do?

CodePudding user response:

it depends on the next action.

You want to call js function on the list view:

def jump_to_src_code(*args, **kwargs):
    print('it works in python')

@admin.register(Record)
class ControlRecord(admin.ModelAdmin):
    list_display = ["file_path", "go_to_src_code", "func_info", "line"]
    search_fields = ['file_path', 'func_info']
    # list_filter = ['severity', 'is_misinformation']
    actions = [jump_to_src_code]

    class Media:
        js = ('myjs.js')

    def go_to_src_code(self, obj):
        return mark_safe('<button onclick= "alert(\'it works in js\'); // call function from myjs.js" >Go</button>')
    go_to_src_code.short_description = "GoToSrcCode"

by click you start the js: start js

You want call the special admin action:

def jump_to_src_code(*args, **kwargs):
    print('it works in python')

@admin.register(Record)
class ControlRecord(admin.ModelAdmin):
    list_display = ["file_path", "go_to_src_code", "func_info", "line"]
    search_fields = ['file_path', 'func_info']
    # list_filter = ['severity', 'is_misinformation']
    actions = [jump_to_src_code]

    # class Media:
        # js = ('myjs.js')

    def go_to_src_code(self, obj):
        action_name = 'jump_to_src_code'
        action_index_in_action_list = '1'
        return mark_safe(f"""
            <input type="hidden" name="_selected_action" value="{obj.id}">
            <input type="hidden" name="action" value="{action_name}">
            <button type="submit" name="index" value="{action_index_in_action_list}">Go</button>"""
            )
    go_to_src_code.short_description = "GoToSrcCode"

this gives you call your action function in python.

enter image description here

  • Related