Fabrice Jaouën
Fabrice Jaouën

Reputation: 199

Django & Ajax : data get lost between the view and the template

Using Ajax and Django, my data get lost when sent back to my template and I can't retrieve them. Here is my code and the logic : Following the dependent dropdown lists tutorial offered by ["Simple is Better Than Complex"][1] I have implemented an Ajax request. Here is the html code:

 <p class="multiple-choice" id="mandate-city" data-url="{% url 'officials:ajax_load_mandate_city' %}">Local Mandate: {{ form.mandate_city }}</p>

The ajax request is fired from this script:

<script>
    $("#id_departments").change(function (){
        var url = $("#mandate-city").attr("data-url");
        var departmentId = $(this).val();
        $.ajax({
            url: url,
            data: {
                'department': departmentId
            },
        success: function (data){
            $("#id_mandate_city").html(data);
            console.log(data);
        }
        });
    });
</script>

After check with console.log, the data are collected by the script. Then, they reach the view. Here is my view:

def load_mandate_city(request):
    department_id = request.GET.get('department')
    mandate_city = MandateCity.objects.filter(department_id=department_id).order_by("department")
    return render(request, "officials/mandate_city_list.html", {mandate_city: mandate_city})

With a print, I have checked, and the data are treated as planned. Then the data are sent back through the url:

path('ajax/load_mandate_city/', views.load_mandate_city, name="ajax_load_mandate_city")

They seem not to reach the template:

{% for mandate in mandate_city %}
    <option value="{{ mandate.pk}}">{{ mandate.get_mandate_display }}</option>
{% endfor %}

And I could not track them in my script. :-/ Can somebody let me know where the bug is ? Thanks. [1]: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

Upvotes: 0

Views: 60

Answers (1)

ISAAC FINKELSTEIN
ISAAC FINKELSTEIN

Reputation: 39

did you try to return the information in a json object and then render it with client side js? in general when you use ajax (or fetch) you wanna use the information returned so it's better to return it as a data type, if you do want to return the html response you should probably not use ajax but rather a form

Upvotes: 1

Related Questions