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:
<formaction="{% url 'home' %}"method='post'id='year-form'>
{% csrf_token %}
<selectclass="form-select form-select-lg mb-3 dropdown-btn"aria-label="Default select example"name="year"><optionselected>Select Year</option><optionvalue="2017">2017</option><optionvalue="2018">2018</option><optionvalue="2019">2019</option><optionvalue="2020">2020</option></select><divclass="d-grid gap-2"><buttonclass="btn btn-primary btn-lg"type="submit">Button</button></div></form><divid="message"></div><divclass="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"