单个对象的Django管理员操作 [英] Django Admin Actions on single object

查看:58
本文介绍了单个对象的Django管理员操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

管理操作似乎可以在 django 管理界面:

The admin actions seem to work on several items selected in the list view of django admin interface:

就我而言,我想在更改(一项)视图上有一个简单的操作按钮。

In my case I would like to have a simple action button on the change (one item) view.

有没有办法使django管理员操作在那里可用?

Is there a way to make the django admin actions available there?

我知道我可以通过解决此问题来解决到列表视图,然后在其中选择一项。

I know that I can walk around this problem by going to the list view, and select one item there. But it would be more nice to have it directly available.

推荐答案

在应用中为您的模型创建模板。

Create a template for your model in your app.

templates/admin/<yourapp>/<yourmodel>/change_form.html

在此示例中,内容是在更改现有对象时添加按钮。

With this example content to add a button when changing an existing object.

{% extends "admin/change_form.html" %}
{% block submit_buttons_bottom %}
    {{ block.super }}
    {% if original %} {# Only show if changing #}
        <div class="submit-row">
            <a href="{% url 'custom-model-action' original.pk %}">
                 Another action
            </a>
        </div>
    {% endif %}
{% endblock %}

将该操作链接到任何网址和重定向回您的模型更改对象视图。 有关扩展管理模板的更多信息

Link that action to any url and redirect back to your model change object view. More information about extending admin templates.

更新:为现有对象的自定义操作添加了完整的通用用例

urls.py

urlpatterns = [
    url(r'^custom_model_action/(?P<object_pk>\d+)/$',
        core_views.custom_model_action, name='custom-model-action')
]

views.py

from django.urls import reverse
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect

def custom_model_action(request, object_pk):
    messages.info(request, 'Performed custom action!')
    return HttpResponseRedirect(
       reverse('admin:<yourapp>_<yourmodel>_change', args=[object_pk])
    )

这篇关于单个对象的Django管理员操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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