简体   繁体   中英

How to add custom action button in Django admin form and post the information

在此处输入图像描述

I'm new to Django!

I'm using Django Admin. How can I make a new button(near save,...) and post the information and use it in a python script(I am using Django version 2).

admin.py:

admin.site.register(Router)
admin.site.register(Peer, PeerModelAdmin)
admin.site.register(Prefixe, PrefixModelAdmin)

You need to override the change_form_template . Try like this:

class YourModelAdmin(admin.ModelAdmin):
    change_form_template = 'custom_change_form.html'

In custom_change_form.html it should be extended from admin/change_form.html and it can be like this:

{% load i18n %}
{% extends 'admin/change_form.html' %}
    <button> Your Custom Button </button>
    <input type="submit" value="{% trans 'Save' %}" class="default" name="_save">
{% endblock %}

You can add a custom button to "Add" form and "Change" form for a specifc admin.

First, about how to add a custom button to "Add" form and "Change" form for a specifc admin, see How to add a custom button at the bottom of "Add" form and "Change" form for a specifc admin or How to add a custom button right next to "SAVE" button on "Add" form and "Change" form for a specifc admin

Next, set "response_add()" for "Add" form and "response_change()" for "Change" form in "class PersonAdmin(admin.ModelAdmin):" to define the action after pressing a custom button as shown below. *Whether or not setting "response_add()" and "response_change()" , inputted data to fields is saved after pressing a custom button:

# "admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    change_form_template = "admin/custom_change_form.html"
    
    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        extra_context = extra_context or {}
        
        extra_context['custom_button'] = True
        
        return super().changeform_view(request, object_id, form_url, extra_context)

    def response_add(self, request, obj, post_url_continue=None):

        if "_custom_button" in request.POST:
            # Do something
            return super().response_add(request, obj, post_url_continue)
        else:
            # Do something
            return super().response_add(request, obj, post_url_continue)

    def response_change(self, request, obj):
        
        if "_custom_button" in request.POST:
            # Do something
            return super().response_change(request, obj)
        else:
            # Do something
            return super().response_change(request, obj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM