gpt4 book ai didi

django - 除了 "change" View 之外,是否有办法让自定义 Django 管理操作出现在 "change list" View 上?

转载 作者:行者123 更新时间:2023-11-28 19:36:01 26 4
gpt4 key购买 nike

无论出于何种原因,我认为这很容易做到,但我仔细观察后发现似乎没有直接的方法允许用户在实例的“更改” View 上执行自定义管理操作(即当您只是查看单个实例的编辑屏幕,而不是实例列表)。

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

最佳答案

这里是this的更新和改进回答。它适用于 django 1.6 并重定向到您来自的地方。

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 - 除了 "change" View 之外,是否有办法让自定义 Django 管理操作出现在 "change list" View 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2805701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com