问题描述
我想在管理界面的添加/更改表单中添加自定义按钮.默认只有三个:
I want to add custom buttons to the add/change form at the administration interface. By default, there are only three:
保存并添加另一个
Save and add another
保存并继续编辑
保存
我在 forms.py
文件中创建了一些自定义方法,我想创建按钮来调用这些方法.我使用了片段 http://djangosnippets.org/snippets/1842/,但并不完全是我想要的是.这个允许从 admin.py
文件而不是 forms.py
.
I have created some custom methods in my forms.py
file, and I want to create buttons to call these methods. I have used the snippet http://djangosnippets.org/snippets/1842/, but it's not exactly what I want. This one allows to create buttons and call methods from the admin.py
file and not forms.py
.
有没有办法做到这一点?
Is there a way to do that?
这是我的 admin.py
代码:
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = { "alias": ("title",) }
form = CategoryForm
admin.site.register(Category, CategoryAdmin)
还有我的 forms.py
代码,
class CategoryForm(forms.ModelForm):
"""
My attributes
"""
def custom_method(self):
print("Hello, World!")
如何创建一个调用custom_method()"的按钮?
How do I create a button that calls "custom_method()"?
推荐答案
您可以覆盖 admin/change_form.html
.将 contrib.admin.templates
中的版本复制到您的项目中.我的是 myproject/templates/admin/change_form.html
,但你可以使用 /myproject/myapp/templates/admin/change_form.html
.
You can override admin/change_form.html
. Copy the version in contrib.admin.templates
into your project. Mine is myproject/templates/admin/change_form.html
, but you could use /myproject/myapp/templates/admin/change_form.html
.
接下来,编辑副本并将对现有模板标签 {% submit_row %}
的两个引用更改为指向您自己的模板标签 {% my_template_tag %}代码>.
Next, edit the copy and change the two references to the existing template tag, {% submit_row %}
, to point to your own template tag, {% my_template_tag %}
.
将您的模板标签基于 contrib.admin
的 {% submit_row %}
,但编辑 HTML 模板以包含您想要显示的任何额外按钮.
Base your template tag on the contrib.admin
's {% submit_row %}
, but edit the HTML template to contain any extra buttons you want to display.
这篇关于在 Django 的 admin change_form 中创建自定义按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!