简体   繁体   中英

Dependent forms in Django using AJAX

In my project I am trying to add a dependent forms solution from this answer . My template seems to accept all data correctly, but it is not displayed in the city field.

Models

class Country(models.Model):
    name = models.CharField(max_length=50)
    def __unicode__(self):
        return u'%s' % (self.name)


class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    def __unicode__(self):
        return u'%s' % (self.name)

urls

path('getdetails/', views.getdetails, name='getdetails'),
path('new-post/', views.new_post, name='new_post'),

views

from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpResponse

def new_post(request):
    countries = Country.objects.all()
    [...]

def getdetails(request):
    #country_name = request.POST['country_name']
    country_name = request.GET['cnt']

    result_set = []
    all_cities = []
    answer = str(country_name[1:-1])
    selected_country = Country.objects.get(name=answer)
    print("selected country name ", selected_country)
    all_cities = selected_country.city_set.all()
    print(all_cities)
    for city in all_cities:
        print("city name", city.name)
        result_set.append({'name': city.name})
    return HttpResponse(JsonResponse({'result_set': result_set}))

templates

  <select name="selectcountries" id="selectcountries">
    {% for item in countries %}
    <option val="{{ item.name }}"> {{ item.name }} </option>
    {% endfor %}
  </select>

  <select name="selectcities" id="selectcities">
  </select>
  
  <!-- and jquery -->
  <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
  <script>
    $(document).ready(function() {
      $('select#selectcountries').change(function() {
        var optionSelected = $(this).find("option:selected");
        var valueSelected = optionSelected.val();
        var country_name = optionSelected.text();


        data = {
          'cnt': country_name
        };
        ajax('/getdetails', data, function(result) {

          console.log(result);
          $("#selectcities option").remove();
          for (var i = result.length - 1; i >= 0; i--) {
            $("#selectcities").append('<option>' + result[i].name + '</option>');
          };


        });
      });
    });
  </script>

As you can see, my template receives AJAX responses, but doesn't match the form, and all cities are always undefinied. How do I fix my error to show the correct cities? https://www.awesomescreenshot.com/video/2878370?key=0b43f35b4587436854d2fbe2ae317b6f (video)

The call back to ajax returns the response. You need to access the result_set yet.

    ajax('/getdetails', data, function(response) {
      console.log(response);
      $("#selectcities option").remove();
      for (var i = response.result_set.length - 1; i >= 0; i--) {
        $("#selectcities").append('<option>' + response.result_set[i].name + '</option>');
      };

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM