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 容器类型是什么?) 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
