How to put a button on List page for each row in django admin page
Asked Answered
M

1

5

I want to add a button for each row as shown in the picture on the button place which shall give a popup of a field content of the same modal or whatever i insert for it to show.

enter image description here

Monahan answered 27/5, 2020 at 15:52 Comment(0)
O
11

This is actually, quite easy to do :) Although depending upon what you want the button to do, it might get a bit more complicated. You can have anything you want in your list view, just create a method that returns whatever you want to insert, and list it in list_display. For example:

class MyModelAdmin(admin.ModelAdmin):
    list_display = (
        "post_title",
        ...
        "my_button_field",
    )

    def my_button_field(self, obj):
        # obj is the particular instance of the object representing a particular row
        return obj.property

In the case of a button, you'll want to use format_html. This will mark the relevant parts of the string safe, and so that it's displayed as an HTML button, and escape the other parts to protect against various securit issues.

It will look something like this:

from django.utils.html import format_html

class MyModelAdmin(admin.ModelAdmin):
    list_display = (
        "post_title",
        ...
        "my_button_field",
    )

    def my_button_field(self, obj):
        return format_html(
            "<button onclick=`doSomething({})`>{}</button>", 
            obj.id, 
            obj.some_property
        )

The values of object.id and object.some_property will get inserted into the placeholders.

Of course you'll need to add the javascript for doSomething, there are afew ways to do that, but you can find out more here. If what you want can be achieved by an anchor, it might be easier to use an <a> tag, and that way you won't have to bother with any additional javascrpt.

Ozellaozen answered 27/5, 2020 at 22:41 Comment(1)
@Monahan No worries. Welcome to SO. If you're happy with the answer, please upvote it and mark it as accepted :)Ozellaozen

© 2022 - 2024 — McMap. All rights reserved.