0

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)

1 Answer 1

1

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>');
      };

    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.