Search code examples
ajaxdjangoformsdjango-formsdynamic-list

Update form values in Django without reloading page?


I'm currently working on a project in Django and currently I'm working on a form that includes several elements. Each element is dynamic and needs to have it's options updated when the element above it changes value. I know I can use AJAX to update the elements contents whenever another one is changed in value, but I was wondering if there was a more Django way, or anyway to do this server side? My main goal is to do it without reloading the entire page each time, any feedback is appreciated. Thanks!

Update: My question is very similar to Django ajax form, choicefields dependancy But I don't fully understand what's going on in the answer. If someone could explain it in a little more detail, that would solve all of my problems for now. I'm trying what that answer says, but I'm getting 500 and 403 errors when I try to load it.

Follow Up: Apparently all of my issues were coming from an outdated jQuery library, once I updated it, everything worked again!


Solution

  • AFAIK there isn't a canonical Django way of doing Ajax… But it's fairy straight forward to do yourself:

    First you've got to create a view which returns whatever JSON data will be needed to update the view. For example, the list of cities in a province:

    from django.utils import simplejson as json
    
    def list_cities(request):
        cities = city_names_in_province(request.GET["province"])
        return json.dumps(cities)
    

    Second you've got to call that view from the HTML (assuming jQuery):

    <select id="provinces">
        …
    </select>
    
    <select id="cities" disabled="true">
        <option>---</option>
    </select>
    
    <script>
    $("#provinces").change(function() {
        var province = $(this).val();
        $.getJSON("{% url list_cities %}", { province: province }, function(cities) {
            var cities_select = $("#cities");
            … put the `cities` list into the `cities_select` …
        });
    });
    </script>
    

    And, apart from the “prettying up” and error checking (eg, what happens if the call to list_cities fails?), that's basically all there is to it.