1

I want to print the data received in the post request on cart_change_form.html, but I have not been able to solve it for a few days.

It was confirmed that the data came in normally up to the changeform_view of admin.py, but only empty values, the data before the POST request, are displayed in cart_change_form.html.

Please tell me how can i print the data after POST request to cart_change.form.html.

#admin.py

def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        extra_context = {'title': 'Cart Add'}
        extra_context['show_save_and_add_another'] = False
        if request.method == 'POST':
            data = json.loads(request.body)
            extra_context['data'] = data
            print(extra_context['data']) # I successfully got data here
        return super(CartAdmin, self).changeform_view(request, object_id, form_url, extra_context=extra_context)

#cart_change_form.html

{% extends 'admin/change_form.html' %}
{% url 'admin:app_list' app_label=opts.app_label %}
{% load i18n admin_urls static admin_modify jazzmin %}
{% get_jazzmin_settings request as jazzmin_settings %}
{% block cart_extrajs %}
<script type="text/javascript">

    if("{{ data }}"){ # empty value is returned
        alert("hi");
    }
    
</script>
{% endblock %}
Jo Jay
  • 123
  • 1
  • 3
  • 14
  • This link can help you: https://stackoverflow.com/questions/31151229/django-passing-json-from-view-to-template – Tonio Nov 10 '21 at 07:06

1 Answers1

0

You can use session to pass structured data trough views in Django.

def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
    # Some code ...
    if request.method == 'POST':
        # Some code here ...
        session['change_form_data'] = request.body
    return super(CartAdmin, self).changeform_view(request, object_id, form_url, extra_context=extra_context)

cart_change_form.html

<script type="text/javascript">
// Access to the session data here
let data = "{{ request.session.change_form_data }}"

if(data){
    // Use data here
    alert("hi");
}

</script>

Note : This is fine only if you want to check the existence. But it gets hard if you wanna use the data, like you want save a json in the django view and use it in js. Because of some troubles about data serialization. In the script above, if you do console.log(data);. You can be surprised by the content because of html special chars (&amp;, &quot;, &lt;, &gt; ...) inside.

Rvector
  • 2,312
  • 1
  • 8
  • 17
  • Thank you for your answer!! But I have one more question. I successfully got data after I followed source code you uploaded. However I needed to refresh cart_change_form.html to get and check the data in console... I want to know why I needed to refresh cart_change_form.html – Jo Jay Nov 11 '21 at 02:00