Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an extra button to one object in django admin

I hope this hasn't been asked and I just missed it, but I searched a bunch and couldn't find anything.

I'm adding an extra save button to the django admin when adding or changing an object. Doing that is fairly easy. I just overrode the submit_line.html to add the extra button and then overrode the save_model function to check for the name of that button. It works great.

My problem is that I only need this button to appear for one particular object... not all of them. I looked in change_form.html to see how it knows what object it is dealing with and found {{ opts.module_name }}, but it doesn't seem to be accessible in submit_line.html. I tried printing it out and nothing showed up.

I also thought about hacking save_as (not very graceful, but I don't really care for this particular project), but that button only shows up on change.. not on add, so that won't work.

Does anyone know how to detect what object I'm working with in submit_line.html? Or any other way of doing this?

Thanks!

like image 703
lovefaithswing Avatar asked Jan 27 '26 06:01

lovefaithswing


1 Answers

You can do it using javascript like this:

/static/js/useful.js

$(document).ready(function ($) {
    $('input[name="_addanother"]').before('<input type="submit" name="_use" value="Useful functionality"/>');
});

and in your ModelAdmin add:

class MyModelAdmin(admin.ModelAdmin):
     class Media:
        js = ('/static/js/useful.js',)
like image 193
luckyjazzbo Avatar answered Jan 29 '26 18:01

luckyjazzbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!