Adding an extra button to one object in django admin

风流意气都作罢 提交于 2019-12-21 20:36:05

问题


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!


回答1:


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',)



回答2:


You should be able to access the original object in change_view's context through original. For example {{ original.id }} should print its id!



来源:https://stackoverflow.com/questions/3874231/adding-an-extra-button-to-one-object-in-django-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!