Add some data to extra_context in response_change

I have some model:

from django.db import models

class Deviation(models.Model):
    name = models.CharField(max_length=100)

    def calc(self):
        # some calculation
        return 1

Then I added a button that runs calc method (overrided change form):

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

{% block submit_buttons_bottom %}
    {{ block.super }}
    <div class="submit-row">
            <input type="submit" value="Calculate" name="calc">
    </div>
    Calculation result: {{ result }}
{% endblock %}

This model is registered in admin with handling calc button submit (pass result in extra_context):

@admin.register(Deviation)
class DeviationAdmin(admin.ModelAdmin):
    change_form_template = 'admin/deviations_change_form.html'
    list_display = '__str__',

    def response_change(self, request, obj):
        if "calc" in request.POST:
            obj.save()
            result = obj.calc()
            return self.change_view(request, str(obj.id), form_url='', extra_context={'result': result})
        return super().response_change(request, obj)

Here problem happening. I cannot render change view with result through extra_context.

How can I pass extra_context to change view?

Back to Top