Search code examples
djangodjango-modelsdjango-admindjango-modeladmin

How can I get custom form field value from within Django Admin's response_change?


I've added a custom functionality to a model by overriding change_form.html. Basically, I'm letting users change the objects of a model if these changes were approved by the admin. I added two buttons, named accept-suggestion and decline-suggestion and I intend to handle the custom functionality through response_change method:

def response_change(self, request, obj):
    if "decline-suggestion" in request.POST:
        # do stuff...

    if "accept-suggestion" in request.POST:
        # do stuff...

Both buttons will send an e-mail to the user saying if the suggestion was declined or approaved. So far so good. The problem is that I want to add the possibility to the admin write a brief justification explaining why the suggestion was declined. So I changed change_form.html again.

<div class="submit-row">
    <div class="float-left">
        <a class="decline-button-outlined accordion" type="button" href="#">DECLINE SUGGESTION</a>
    </div>
    <div class="float-right">
        <input class="accept-button" type="submit" name="accept-suggestion" value="ACEITAR SUGESTÃO">
    </div>
</div>

<div class="additional-infos">
    <fieldset class="module aligned">
        <div class="form-row">
            <label for="decline-reasons">Reasons for rejection:</label>
            <textarea
                placeholder="If you find necessary, provide information on the reasons that led to the rejection of the suggestion"
                id="decline-reasons" class="vLargeTextField" rows="5"></textarea>
        </div>
        <div class="submit-row">
            <div class="float-right">
                <input class="decline-button" type="submit" name="decline-suggestion" value="DECLINE">
            </div>
        </div>
    </fieldset>
</div>

Is this the best approach? If so, how can I get the value of the <textarea> above from within response_change? If not, what would you suggest?

Thank you very much!


Solution

  • If you add a name to your <textarea> you will be able to retrieve the contents on the server side. Without a name, the data is not being sent to the server (Django).

    So something like this:

    <textarea
        placeholder="If you find necessary, provide information on the reasons that led to the rejection of the suggestion"
        id="decline-reasons" name="decline-reasons" class="vLargeTextField" rows="5"></textarea>
    

    Should allow you to retrieve the text on the Django side with request.POST["decline-reasons"].