有没有办法让自定义 Django 管理操作出现在“更改"上?除了“更改列表"之外,还可以查看看法? [英] Is there a way to get custom Django admin actions to appear on the "change" view in addition to the "change list" view?

查看:12
本文介绍了有没有办法让自定义 Django 管理操作出现在“更改"上?除了“更改列表"之外,还可以查看看法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论出于何种原因,我认为这很容易做到,但我看得更深入,似乎没有直接的方法允许用户在实例的更改"视图上执行自定义管理操作(即,当您只是查看单个实例的编辑屏幕,而不是实例列表).

I thought for whatever reason this would be easy to do, but I looked deeper and it appears there is no straightforward way to allow users to execute custom admin actions on the "change" view of an instance (i.e. when you are just viewing the edit screen for a single instance, not the list of instances).

我是否忽略了一种简单的方法来做到这一点?还是我唯一的选择是覆盖其中一个管理模板(可能还有 ModelAdmin.add_view 方法)?

Am I overlooking an easy way to do this? Or is my only choice to override one of the admin templates (and probably the ModelAdmin.add_view method)?

推荐答案

这里是 this 答案的更新和改进.它适用于 django 1.6 并重定向到您的来源.

Here is update and improvement of this answer. It works with django 1.6 and redirects to where you came from.

class ActionInChangeFormMixin(object):
    def response_action(self, request, queryset):
        """
        Prefer http referer for redirect
        """
        response = super(ActionInChangeFormMixin, self).response_action(request,
                queryset)
        if isinstance(response, HttpResponseRedirect):
            response['Location'] = request.META.get('HTTP_REFERER', response.url)
        return response  

    def change_view(self, request, object_id, extra_context=None):
        actions = self.get_actions(request)
        if actions:
            action_form = self.action_form(auto_id=None)
            action_form.fields['action'].choices = self.get_action_choices(request)
        else: 
            action_form = None
        extra_context=extra_context or {}
        extra_context['action_form'] = action_form
        return super(ActionInChangeFormMixin, self).change_view(request, object_id, extra_context=extra_context)

class MyModelAdmin(ActionInChangeFormMixin, ModelAdmin):
    ......

模板:

{% extends "admin/change_form.html" %}
{% load i18n admin_static admin_list admin_urls %}

{% block extrastyle %}
  {{ block.super }}
  <link rel="stylesheet" type="text/css" href="{% static "admin/css/changelists.css" %}" />
{% endblock %}

{% block object-tools %}
    {{ block.super }}
    <div id="changelist">
    <form action="{% url opts|admin_urlname:'changelist' %}" method="POST">{% csrf_token %}
        {% admin_actions %}
        <input type="hidden" name="_selected_action" value="{{ object_id }}">
    </form>
    </div>
{% endblock %}

这篇关于有没有办法让自定义 Django 管理操作出现在“更改"上?除了“更改列表"之外,还可以查看看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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