0

I would like to add a custom button X along with Save button in admin form and whenever I click the button X I want to save the current data and send an email.

I don't want to send email after every save so cannot use post_save signals. I am able to add the custom button. How can I add this functionality for button X in the detail page?

minglyu
  • 2,958
  • 2
  • 13
  • 32

1 Answers1

1

You can override admin/change_form.html, check how to Overriding admin templates

In admin/change_form.html, you can find this line:

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

{% submit_row %} is where the list of buttons are rendered out, you can start by extending the change_form to add a new button:

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

{% block submit_buttons_bottom %}
    {{ block.super }} <!-- or simply {% submit_row %} -->
     
    <div class="submit-row">
      <input type="submit" value="X" name="_button_x">
    </div>
{% endblock %}

After you have added the new button, you can specify what template is going to be used for the change page.

response_change is called after the admin form is submitted and just after the object and all the related instances have been saved. You can override it to change the default behavior after the object has been changed.

@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
    # specify the new template you would like to use
    change_form_template = "<change_form_template>"

    def response_change(self, request, obj):
        if "_button_x" in request.POST:
            # customization here
            ...
        return super().response_change(request, obj)

You can read more here

minglyu
  • 2,958
  • 2
  • 13
  • 32