python 如何添加执行Django管理动作的自定义按钮来更改表单页面?

vs91vp4v  于 2023-05-16  发布在  Python
关注(0)|答案(5)|浏览(165)

我已经为我的模型定义了一个自定义的管理操作,它可以像预期的那样完美地工作。我还研究了在SO上向管理更改表单页面添加按钮的多种方法。我唯一缺少的步骤是如何在更改表单页面中的按钮执行我的自定义管理操作与当前对象?
目标是允许管理员单独检查每个对象并对它们执行操作,而无需返回列表视图,选择检查的对象并执行列表中的操作。
我的自定义管理操作如下所示:

def admin_apply_change(modeladmin, request, queryset):
    # loop over objects in query set and perform action

我假设有一种简单而干净的方法可以在管理员更改表单中调用此操作,其中queryset将仅包含管理员正在查看的当前打开的对象。

**注意:**如果按钮位于变更表单的底部,靠近Save按钮,而不是位于顶部,History不太明显,则会更好。

解决方案:

See the answer below乘以Remi得到解。为了使其工作,需要进行以下更正:
1.在response_change的覆盖中,一些变量的初始化丢失:

opts = self.model._meta
pk_value = obj._get_pk_val()
preserved_filters = self.get_preserved_filters(request)

1.新的包含标签custom_submit_row应该放在templatetags中,而不是admin中(请参阅docs for custom templatetags
1.这是你可能会浪费一些时间的疏忽。在change_form.html中,您不仅需要更改建议的行:

{% if save_on_top %}{% block submit_buttons_top %}{% submit_row %}{% endblock %}{% endif %}

还有底部submit_row出现的更重要的一行:

{% block submit_buttons_bottom %}{% submit_row %}{% endblock %}
  • 它位于change_form.html中javascript块的正上方。*
kqqjbcuj

kqqjbcuj1#

您可以查看change_form_template并将其设置为您的自定义模板,然后覆盖response_change方法:

class MyModelAdmin(admin.ModelAdmin):

    # A template for a customized change view:
    change_form_template = 'path/to/your/custom_change_form.html'

    def response_change(self, request, obj):
        opts = self.model._meta
        pk_value = obj._get_pk_val()
        preserved_filters = self.get_preserved_filters(request)

        if "_customaction" in request.POST:
            # handle the action on your obj
            redirect_url = reverse('admin:%s_%s_change' %
                               (opts.app_label, opts.model_name),
                               args=(pk_value,),
                               current_app=self.admin_site.name)
             redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
             return HttpResponseRedirect(redirect_url)
        else:
             return super(MyModelAdmin, self).response_change(request, obj)

site-packages/django/contrib/admin/templates/change_form.html复制change_form.html并编辑第40行

{% if save_on_top %}{% block submit_buttons_top %}{% submit_row %}{% endblock %}{% endif %}

{% if save_on_top %}{% block submit_buttons_top %}{% custom_submit_row %}{% endblock %}{% endif %}

也检查行:

{% block submit_buttons_bottom %}{% submit_row %}{% endblock %}

就在javascript块上面。
然后你可以在你的www.example.com中注册一个新的包含标签admin.py或者将它添加到templatetags中:

@register.inclusion_tag('path/to/your/custom_submit_line.html', takes_context=True)
def custom_submit_row(context):
    """
    Displays the row of buttons for delete and save.
    """
    opts = context['opts']
    change = context['change']
    is_popup = context['is_popup']
    save_as = context['save_as']
    ctx = {
        'opts': opts,
        'show_delete_link': (
            not is_popup and context['has_delete_permission'] and
            change and context.get('show_delete', True)
        ),
        'show_save_as_new': not is_popup and change and save_as,
        'show_save_and_add_another': (
            context['has_add_permission'] and not is_popup and
            (not save_as or context['add'])
        ),
        'show_save_and_continue': not is_popup and context['has_change_permission'],
        'is_popup': is_popup,
        'show_save': True,
        'preserved_filters': context.get('preserved_filters'),
    }
    if context.get('original') is not None:
        ctx['original'] = context['original']
    return ctx

您的custom_submit_line.html的内容:

{% load i18n admin_urls %}
<div class="submit-row">
{% 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 %}

<input type="submit" value="{% trans 'Custom Action' %}"  name="_customaction" />

</div>

它有很多代码,但主要是复制/粘贴。希望能帮上忙。

8ljdwjyq

8ljdwjyq2#

大多数人可能会不假思索地这样做,尽管从答案中并不清楚管理员更改表单应该简单地扩展而不是完全覆盖。
custom_change_form.html

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

{% if save_on_top %}{% block submit_buttons_top %}{% custom_submit_row %}{% endblock %}{% endif %}

{% block submit_buttons_bottom %}{% custom_submit_row %}{% endblock %}
4ngedf3f

4ngedf3f3#

或者,您可以扩展 submit_line.html 文件,添加自定义按钮(在更改页面的顶部和底部)。
您的文件 templates/adminyour_app_name/your_model_name.html 将以以下开头:

{% extends "admin/submit_line.html" %}
{% load i18n admin_urls %}
<div class="submit-row">
  {% block submit-row %}  
     ... YOUR BUTTONS HERE ...
  {% endblock %}
</div>
2skhul33

2skhul334#

基于Remi的回答,一个更干净的解决方案,用于在submit_line.html模板中覆盖submit-row

{% extends "admin/submit_line.html" %}
{% load i18n admin_urls %}
<div class="submit-row">
{% block submit-row %}
{{ block.super }}

{% if custom_buttons_template %}{% include custom_buttons_template %}{% endif %}

{% endblock %}

change_view中,您可以将custom_buttons_template添加到上下文中,以便您可以分别在每个模型上自定义自定义按钮。

def change_view(self, request, object_id, form_url='', extra_context=None):
    extra_context = extra_context or {}
    extra_context['custom_buttons_template'] = 'admin/test.html'
    return super(TransactionFileAdmin, self).change_view(
        request, object_id, form_url, extra_context=extra_context,
    )

在此之后,我的模板将加载admin/test.html并将内容直接插入到Save按钮之前的提交行中。如果你想把你的按钮放在其他地方,你可以复制完整的submit_line.html并把custom_buttons_template放在任何地方。

lztngnrs

lztngnrs5#

在Django Admin中的change页面中,您可以添加运行管理操作的自定义按钮。
例如,首先将submit_line.htmldjango/contrib/admin/templates/admin/submit_line.html复制到templates/admin/templates/admin/app1/templates/admin/app1/person/以覆盖它,如下所示。* templates/admin/templates/admin/app1/templates/admin/app1/person/中的submit_line.html分别适用于所有应用程序中的所有管理员、仅app1中的所有管理员或仅personapp1中的所有管理员,您可以看到原始的submit_line.html

Django Project
 |-core
 |  └-settings.py
 |-app1
 |  |-models.py
 |  └-admin.py 
 |-app2
 └-templates
    └-admin
       |-app1
       |  |-person
       |  |  └-submit_line.html # Or
       |  |-model1
       |  |-model2
       |  └-submit_line.html # Or
       |-app2
       └-submit_line.html # Or

然后,将{% if custom_button %}<input ...添加到submit_line.html,如下所示:

# "templates/admin/submit_line.html" Or
# "templates/admin/app1/submit_line.html" Or
# "templates/admin/app1/person/submit_line.html"

# ...
{% if show_delete_link and original %}
    {% 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">{% translate "Delete" %}</a></p>
{% endif %} 
{# ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ #}
{% if custom_button %}<input type="submit" value="{% translate 'Custom button' %}" name="_custom_button">{% endif %}
{# ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ #}
{% if show_save_as_new %}<input type="submit" value="{% translate 'Save as new' %}" name="_saveasnew">{% endif %}
{% if show_save_and_add_another %}<input type="submit" value="{% translate 'Save and add another' %}" name="_addanother">{% endif %}
{% if show_save_and_add_another %}<input type="submit" value="{% translate 'Save and add another' %}" name="_addanother">{% endif %}
# ...

然后,在settings.py中的TEMPLATES中设置BASE_DIR / 'templates''DIRS',如下所示:

# "core/settings.py"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'templates' # Here
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

并且,models.py中有Person模型,如下所示:

# "app1/models.py"

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

并且,在admin.py中有Person admin和uppercase admin操作,如下所示:

# "app1/admin.py"

from django.contrib import admin, messages
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    actions = ("uppercase", )

    # Here
    @admin.action(description='Make selected persons uppercase')
    def uppercase(modeladmin, request, queryset):
        for obj in queryset:
            obj.name = obj.name.upper()
            obj.save()
        messages.success(request, "Successfully made uppercase!")

因此,如果您使用uppercase管理操作,如下所示:

然后,您可以将所选人员设置为大写,如下所示:

并且,change页面上尚未显示自定义按钮,如下所示:

现在,覆盖Person admin中的change_view()和response_change(),如下所示。* 您可以看到原始的change_view()和response_change():

# "app1/admin.py"

from django.contrib import admin, messages
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    actions = ("uppercase", )

    @admin.action(description='Make selected persons uppercase')
    def uppercase(modeladmin, request, queryset):
        for obj in queryset:
            obj.name = obj.name.upper()
            obj.save()
        messages.success(request, "Successfully made uppercase!")

    # Here
    def change_view(self, request, object_id, form_url="", extra_context=None):
        extra_context = extra_context or {}
        extra_context['custom_button'] = True
        return self.changeform_view(request, object_id, form_url, extra_context)

    # Here
    def response_change(self, request, obj):
        if "_custom_button" in request.POST:
            queryset = self.get_queryset(request).filter(id=obj.id)
            self.uppercase(request, queryset)
        return super().response_change(request, obj)

然后,在change页面上显示一个自定义按钮,如下所示,然后如果您单击自定义按钮:

然后,您可以使人大写,如下所示:

另外,覆盖Person admin中的add_view()和response_add(),如下所示。* 你可以看到原始的add_view()和response_add():

# "app1/admin.py"

from django.contrib import admin, messages
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    actions = ("uppercase", )

    @admin.action(description='Make selected persons uppercase')
    def uppercase(modeladmin, request, queryset):
        for obj in queryset:
            obj.name = obj.name.upper()
            obj.save()
        messages.success(request, "Successfully made uppercase!")

    # Here
    def add_view(self, request, form_url="", extra_context=None):
        extra_context = extra_context or {}
        extra_context['custom_button'] = True
        return self.changeform_view(request, None, form_url, extra_context)

    # Here
    def response_add(self, request, obj, post_url_continue=None):
        if "_custom_button" in request.POST:
            queryset = self.get_queryset(request).filter(id=obj.id)
            self.uppercase(request, queryset)
        return super().response_add(request, obj, post_url_continue)

然后,add页面上会显示一个自定义按钮,如下所示,然后如果您单击自定义按钮:

然后,您可以使人大写,如下所示:

相关问题