将自定义按钮添加到 Django 应用程序的管理页面

发布于 2024-09-25 00:10:18 字数 147 浏览 2 评论 0原文

我在 Django 中有一个应用程序,其中的例程仅供管理员使用。我想要做的是添加一个按钮来执行管理应用程序的此应用程序部分中的例程。

我是否应该为其制作一个模板,如果是这样的话,如何在管理中为应用程序添加 html 模板。或者也许有一个命令可以简单地添加一个按钮?

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

咆哮 2024-10-02 00:10:19

不要弄乱管理页面。

  1. 为此创建一个“应用程序”。是的,你的功能只是一个“例程”。没关系。许多较小的应用程序是一件好事。

  2. 此应用程序在 models.py 中没有任何新内容。没有新型号。零行代码。

  3. 此应用程序在 urls.py 中有一个有用的 URL。可用于显示此管理页面的东西。一个网址。代码行不多(不到十几行。)

  4. 该应用程序在 views.py 中有一个视图函数。在“GET”上,该视图函数呈现表单。在“POST”上,该视图函数执行“例程”。这是您的应用程序的“核心”。当然,GET 只是返回用于显示的模板。 POST 执行真正的工作,并返回最终状态或其他内容。

该视图函数受装饰器保护,因此只有管理员才能执行它。
请参阅 http://docs.djangoproject。 com/en/1.2/topics/auth/#django.contrib.auth.decorators.user_passes_test。您想为成为管理员编写一个测试。 lambda u: u.is_staff 可能就是这样。

  1. 该应用程序有一个模板,由 GET 和 POST 呈现。该模板包含您的表单和按钮。您无法轻松添加到管理中的模板。

  2. tests.py 是一个有两个用户的测试用例,其中一个是管理员,另一个不是管理员。

不会弄乱内置管理页面。

Don't mess with the admin pages.

  1. Create an "application" for this. Yes, your function is just a "routine". That's okay. Many smaller applications are a good thing.

  2. This application has nothing new in models.py. No new model. Zero lines of code.

  3. 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.)

  4. 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.

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_staff is probably it.

  1. 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.

  2. The tests.py is a test case with two users, one who is an admin and one who is not an admin.

No messing with built-in admin pages.

初与友歌 2024-10-02 00:10:18

处理管理表单可能很复杂,但我通常发现添加链接、按钮或额外信息既简单又有用。 (就像不进行内联的相关对象的链接列表,特别是对于查看次数多于编辑次数的内容)。

来自 Django 文档

由于管理模板的模块化设计,通常
既没有必要也不建议
替换整个模板。这是
几乎总是最好只覆盖
您所选择的模板部分
需要改变。

这将在表单顶部添加一个列表。

放置在 templates/admin/[your_app]/[template_to_override] 中:

{% extends "admin/change_form.html" %}

{% block form_top %}

{% for item in original.items %}
  {{ item }}
{% endfor %}

{% endblock %}

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]:

{% extends "admin/change_form.html" %}

{% block form_top %}

{% for item in original.items %}
  {{ item }}
{% endfor %}

{% endblock %}
亢潮 2024-10-02 00:10:18

Django1.10:

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>

当然,这假设按钮的字符串表示是适当的浏览器输入button 元素,并使用 django.utils.safestring.mark_safe 标记为安全。或者,您可以使用safe 模板过滤器或直接访问button 的属性来构造。在我看来,最好将此类事情隔离到 python 级别。

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,
    )

此方法使您可以轻松地将按钮添加到任何ModelAdmin。作为步骤 (1) 的替代方案,您可以扩展 admin/change_form.html 并覆盖块 submit_row。由于模板中需要额外的标签,这会稍微冗长一些。

如果您希望在所有模型(或特定子集)上使用额外的操作,则使用所需的功能对 ModelAdmin 进行子类化(例如向模型添加归档。您甚至可以添加覆盖对于删除 - 以及其他默认按钮 - 以便存档而不是删除模式;这将需要一些模板修改)

Django1.10:

1) Override 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 input or button element, and is marked safe with django.utils.safestring.mark_safe. Alternatively, you could use the safe template filter or access the attributes of button directly to construct the <input>. In my opinion, it's better to isolate such things to the python level.

2) Override 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 ModelAdmin easily. Alternatively to step (1), you could extend admin/change_form.html and override block submit_row. This would be slightly more verbose due to extra tags required in the template.

If you want the extra action available across all of your models (or a specific subset) then subclass ModelAdmin with 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)

白况 2024-10-02 00:10:18

您还可以使用 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')

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:

# 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')
网名女生简单气质 2024-10-02 00:10:18

如果合适,您可以考虑为此类对象添加自定义管理操作(类似于内置的“删除”)。一些好处包括:“纯 Django”,不必弄乱模板,并且能够同时作用于多个对象。

Django 的管理允许您编写和注册“操作”——简单
使用在上选择的对象列表调用的函数
更改列表页面。如果您查看管理员中的任何更改列表,您会
查看此功能的实际应用; Django 附带了“删除选定的
对象”操作适用于所有模型。

https://docs.djangoproject.com/en/dev/ref /contrib/admin/actions/

我从这篇文章中得到了关于如何添加自定义操作按钮的想法,这是另一个答案。不过,我能够通过更简单的内置操作来完成。

https://medium.com /@hakibenita/如何将自定义操作按钮添加到django-admin-8d266f5b0d41

You might consider adding a custom admin action for 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’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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文