Ajax In Django Is Creating Duplicate Elements
I have a form which when submitted creates a graph using Plotly. I am trying to use Ajax to submit the form without page refresh. While the form is submitted successfully, the form
Solution 1:
You should use a different endpoint/view to return the graph template. At the moment you are getting the current page and loading it again but with a graph this time.
Your home template should be:
<form action="{% url 'home' %}" method='post' id='year-form'>
{% csrf_token %}
<select class="form-select form-select-lg mb-3 dropdown-btn" aria-label="Default select example"
name="year">
<option selected>Select Year</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<div class="d-grid gap-2">
<button class="btn btn-primary btn-lg" type="submit">Button</button>
</div>
</form>
<div id="message"></div>
<div class="graph center" id='graph'>
<p>No graph was provided.</p>
</div>
Then you have a second template used at a different view which you get via ajax to get the graph like so:
{% if graph %}
{{ graph.0|safe }}
{% else %}
<p>No graph was provided.</p>
{% endif %}
Post a Comment for "Ajax In Django Is Creating Duplicate Elements"