Python 将自定义按钮添加到 Django 应用程序的管理页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3780737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a custom button to a Django application's admin page
提问by Alexandre Deschamps
I have an application in Django with a routine which would be available only to the admin. What I want to do is add a button to perform the routine in this application's section of the admin app.
我在 Django 中有一个应用程序,它有一个只对管理员可用的例程。我想要做的是在管理应用程序的这个应用程序部分添加一个按钮来执行例程。
Am I supposed to make a template for it, and if that's the case, how do I add a html template for an app in the admin. Or maybe there's a command to simply add a button?
我是否应该为它制作一个模板,如果是这样,我该如何在 admin.js 中为应用程序添加 html 模板?或者也许有一个命令可以简单地添加一个按钮?
采纳答案by Lincoln B
Messing with the admin forms can be complicated but i've commonly found that adding links, buttons, or extra info is easy and helpful. (Like a list of links to related objects witout making an inline, esp for things that are more viewed than edited).
处理管理表单可能很复杂,但我发现添加链接、按钮或额外信息很容易且很有帮助。(就像在不进行内联的情况下指向相关对象的链接列表,尤其是查看次数多于编辑次数的内容)。
From Django docs
Because of the modular design of the admin templates, it is usually neither necessary nor advisable to replace an entire template. It is almost always better to override only the section of the template which you need to change.
由于管理模板的模块化设计,通常不需要也不建议替换整个模板。仅覆盖模板中需要更改的部分几乎总是更好。
This will add a list over the top of the form.
这将在表单顶部添加一个列表。
Place in templates/admin/[your_app]/[template_to_override]:
放置在templates/admin/[your_app]/[template_to_override]:
{% extends "admin/change_form.html" %}
{% block form_top %}
{% for item in original.items %}
{{ item }}
{% endfor %}
{% endblock %}
回答by S.Lott
Don't mess with the admin pages.
不要弄乱管理页面。
Create an "application" for this. Yes, your function is just a "routine". That's okay. Many smaller applications are a good thing.
This application has nothing new in
models.py. No new model. Zero lines of code.This application has a useful URL in
urls.py. Something that can be used to display this admin page. One URL. Not many lines of code (less than a dozen.)This application has one view function in
views.py. On "GET", this view function presents the form. On "POST", this view function does the "routine". This is the "heart" of your application. The GET -- of course -- simply returns the template for display. The POST does the real work, and returns a final status or something.
为此创建一个“应用程序”。是的,您的功能只是一个“例程”。没关系。许多较小的应用程序是一件好事。
此应用程序在
models.py. 没有新型号。零行代码。此应用程序在
urls.py. 可用于显示此管理页面的东西。一个网址。代码行不多(不到一打。)此应用程序在
views.py. 在“GET”上,此视图函数呈现表单。在“POST”上,此视图函数执行“例程”。这是您的应用程序的“心脏”。GET —— 当然 —— 简单地返回用于显示的模板。POST 做真正的工作,并返回一个最终状态或其他东西。
This view function is protected with a decorator so that only an admin can execute it.
See http://docs.djangoproject.com/en/1.2/topics/auth/#django.contrib.auth.decorators.user_passes_test. You want to write a test for being an admin. lambda u: u.is_staffis probably it.
此视图函数受装饰器保护,因此只有管理员才能执行它。请参阅http://docs.djangoproject.com/en/1.2/topics/auth/#django.contrib.auth.decorators.user_passes_test。您想为成为管理员编写测试。 lambda u: u.is_staff大概是吧。
This application has one template, presented by the GET and POST. That template has your form with your button. The one you can't add to admin easily.
The
tests.pyis a test case with two users, one who is an admin and one who is not an admin.
该应用程序有一个模板,由 GET 和 POST 提供。该模板具有带有按钮的表单。您无法轻松添加到管理员的那个。
这
tests.py是一个有两个用户的测试用例,一个是管理员,一个不是管理员。
No messing with built-in admin pages.
不会弄乱内置的管理页面。
回答by saulobrito
You can also use django-admin-tools, which allows you to easily customize the admin front page like a dashboard. Using a LinkList, you can point to some view method and check if the user is authenticated. It goes like thies:
您还可以使用django-admin-tools,它允许您像仪表板一样轻松自定义管理首页。使用 LinkList,您可以指向某个视图方法并检查用户是否已通过身份验证。它是这样的:
# dashboard.py (read more about how to create one on django-admin-tools docs)
class CustomIndexDashboard(Dashboard):
"""
Custom index dashboard for captr.
"""
def init_with_context(self, context):
self.children.append(modules.LinkList(
_('Tasks'),
children=[
['Your task name', '/task']
]
))
# urls.py (mapping uri to your view function)
urlpatterns += patterns('yourapp.views',
(r'^task$', 'task'),
)
# views.py
def task(request):
if request.user.is_authenticated():
update_definitions_task.delay() # do your thing here. in my case I'm using django-celery for messaging
return redirect('/admin')
回答by DylanYoung
Django1.10:
Django1.10:
1) Override admin/submit_line.html:
1)覆盖admin/submit_line.html:
{% load i18n admin_urls %}
<div class="submit-row">
{% if extra_buttons %}
{% for button in extra_buttons %}
{{ button }}
{% endfor %}
{% endif %}
{% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %}
{% if show_delete_link %}
{% url opts|admin_urlname:'delete' original.pk|admin_urlquote as delete_url %}
<p class="deletelink-box"><a href="{% add_preserved_filters delete_url %}" class="deletelink">{% trans "Delete" %}</a></p>
{% endif %}
{% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" />{% endif %}
{% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" />{% endif %}
{% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" />{% endif %}
</div>
This assumes, of course, that button's string representation is an appropriate browser inputor buttonelement, and is marked safe with django.utils.safestring.mark_safe. Alternatively, you could use the safetemplate filter or access the attributes of buttondirectly to construct the <input>. In my opinion, it's better to isolate such things to the python level.
当然,这假设它button的字符串表示是合适的浏览器input或button元素,并用 标记安全django.utils.safestring.mark_safe。或者,您可以使用safe模板过滤器或button直接访问 的属性来构造<input>. 在我看来,最好将这些东西隔离到 python 级别。
2) Override MyModelAdmin.change_view:
2)覆盖MyModelAdmin.change_view:
def change_view(self, request, object_id, form_url='', extra_context=None):
extra_context = extra_context or self.extra_context()
return super(PollAdmin, self).change_view(
request, object_id, form_url, extra_context=extra_context,
)
This method enables you to add buttons to any ModelAdmineasily. Alternatively to step (1), you could extend admin/change_form.htmland override block submit_row. This would be slightly more verbose due to extra tags required in the template.
此方法使您可以ModelAdmin轻松地向任何按钮添加按钮。作为步骤 (1) 的替代方法,您可以扩展admin/change_form.html和覆盖 block submit_row。由于模板中需要额外的标签,这会稍微冗长一些。
If you want the extra action available across all of your models (or a specific subset) then subclass ModelAdminwith the desired functionality (an example would be to add archiving to your models. You could even add an override for delete--and the other default buttons--so that the mode is archived instead of deleted; this would require some template modifications)
如果您希望在所有模型(或特定子集)中使用额外的操作,然后ModelAdmin使用所需的功能进行子类化(例如将归档添加到模型中。您甚至可以为删除添加覆盖 - 以及另一个默认值按钮——这样模式就被归档而不是被删除;这需要一些模板修改)
回答by John Lehmann
You might consider adding a custom admin actionfor this kind of object (similar to the built in 'delete'), if appropriate. Some benefits include: "pure Django", not having to mess with templates, and being able to act on multiple objects at once.
如果合适,您可以考虑为此类对象添加自定义管理操作(类似于内置的“删除”)。一些好处包括:“纯 Django”,不必弄乱模板,并且能够一次对多个对象进行操作。
Django's admin lets you write and register “actions” – simple functions that get called with a list of objects selected on the change list page. If you look at any change list in the admin, you'll see this feature in action; Django ships with a “delete selected objects” action available to all models.
Django 的管理员允许您编写和注册“动作”——简单的函数,这些函数使用在更改列表页面上选择的对象列表来调用。如果您查看管理中的任何更改列表,您将看到此功能正在运行;Django 附带了一个“删除选定对象”操作,适用于所有模型。
https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/
https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/
I got the idea from this article on how to add a custom action button, which is another answer all together. I was able to get by with the simpler built-in actions though.
我从这篇文章中得到了关于如何添加自定义操作按钮的想法,这是另一个答案。不过,我能够使用更简单的内置操作。
https://medium.com/@hakibenita/how-to-add-custom-action-buttons-to-django-admin-8d266f5b0d41
https://medium.com/@hakibenita/how-to-add-custom-action-buttons-to-django-admin-8d266f5b0d41

