在Django的admin change_form中创建自定义按钮 [英] Create custom buttons in admin change_form in Django

查看:1724
本文介绍了在Django的admin change_form中创建自定义按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在管理界面添加自定义按钮到添加/更改表单。默认情况下,只有三个:




  • 保存并添加另一个


  • 保存并继续编辑


  • 保存




我已经在我的 forms.py 文件中创建了一些自定义方法,我想创建一些按钮来调用这些方法。我已经使用 http://djangosnippets.org/snippets/1842/ 的代码段,但它不完全是我想要的是。这个允许从 admin.py 文件创建按钮和调用方法,而不是 forms.py



有没有办法这样做?



这是我的 admin.py 代码:

  class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {alias:( title,)}
form = CategoryForm

admin.site.register(Category,CategoryAdmin)

我的 forms.py 代码

  class CategoryForm(forms.ModelForm):

我的属性

def custom_method(self):
print ,World!)

如何创建一个调用custom_method()的按钮? p>

解决方案

您可以覆盖 admin / change_form.html 。将 contrib.admin.templates 中的版本复制到您的项目中。 Mine是 myproject / templates / admin / change_form.html ,但您可以使用 /myproject/myapp/templates/admin/change_form.html

接下来,编辑该副本并将两个引用更改为现有的模板标签 {%submit_row%} ,指向自己的模板标签, {%my_template_tag%}



contrib.admin {%submit_row%} 中的标签,但编辑HTML模板以包含任何额外的按钮您要显示。


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

  • Save and continue editing

  • Save

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?

This is my admin.py code:

class CategoryAdmin(admin.ModelAdmin):
    prepopulated_fields = { "alias": ("title",) }
    form = CategoryForm

admin.site.register(Category, CategoryAdmin)

And my forms.py code,

class CategoryForm(forms.ModelForm):
    """
    My attributes
    """
    def custom_method(self):
        print("Hello, World!")

How do I create a button that calls "custom_method()"?

解决方案

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.

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 %}.

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中创建自定义按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆