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

查看:16
本文介绍了单个对象上的 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 %}

将该操作链接到任何 url 并重定向回您的模型更改对象视图.更多关于扩展管理模板的信息.

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天全站免登陆