Create custom buttons in admin change_form in Django(在 Django 的 admin change_form 中创建自定义按钮)
问题描述
我想在管理界面的添加/更改表单中添加自定义按钮.默认只有三个:
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 中创建自定义按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Django 的 admin change_form 中创建自定义按钮
基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
