S
S
Stanislav Konovalov2019-05-10 13:33:08
JavaScript
Stanislav Konovalov, 2019-05-10 13:33:08

Django. Dependent dropdown list in JS?

Good day. Tell me, please, what am I doing wrong? You need to make a dependent dropdown list. I did a similar task when it was necessary to make a dependent list in the form, now the same thing needs to be done to search the site. The script is already ready, only I need to redo something, but I just can’t figure out how to do it right. If it's not difficult, please take a look:

class Region(models.Model):
    name = models.CharField(max_length=100, verbose_name='Название области')

    def __str__(self):
        return self.name

class City(models.Model):
    region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область')
    name = models.CharField(max_length=100, verbose_name='Название города')

    def __str__(self):
        return self.name

class District(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город')
    name = models.CharField(max_length=100, verbose_name='Название района')

    def __str__(self):
        return self.name

views.py
def search(request):
    districts = District.objects.all()
    cities = City.objects.all()
    regions = Region.objects.all()
    queryset_list = Listing.objects.order_by('-list_date')

    if 'region' in request.GET:
        region_id = request.GET.get('region')
        cities = City.objects.filter(region_id=region_id).order_by('name')
        if region_id:
            queryset_list = queryset_list.filter(region_id=region_id)

    if 'city' in request.GET:
        city_id = request.GET.get('city')
        districts = District.objects.filter(city_id=city_id).order_by('name')
        if city_id:
            queryset_list = queryset_list.filter(city_id=city_id)

    if 'district' in request.GET:
        district_id = request.GET.get('district')
        if district_id:
            queryset_list = queryset_list.filter(district_id=district_id)

    context = {
        'districts': districts,
        'cities': cities,
        'regions': regions,
        'listings': queryset_list,
        'values': request.GET
    }
    return render(request, 'listings/search.html', context)

Sample:
<form action="{% url 'search' %}" id="search" data-search-url="{% url 'search' %}">    
           <div class="form-row">
            <div class="col-md-3 mb-3">                  
              <label class="sr-only">Область</label>
              <select name="region" class="form-control" id="id_region">
                <option selected="true" disabled="disabled">Область</option>
                {% for region in regions %}
                  <option value="{{ region.pk }}">{{ region.name }}</option>
                {% endfor %}
              </select>
            </div>
            <div class="col-md-3 mb-3">
              <label class="sr-only">Город</label>
              <select name="city" class="form-control" id="id_city">
                <option selected="true" disabled="disabled">Город</option>
                  {% for city in cities %}
                    <option value="{{ city.pk }}">{{ city.name }}</option>
                  {% endfor %}
              </select>
            </div>                
            <div class="col-md-3 mb-3">
              <label class="sr-only">Район</label>
              <select name="district" class="form-control" id="id_district">
                <option selected="true" disabled="disabled">Район</option>
                  {% for district in districts %}
                    <option value="{{ district.pk }}">{{ district.name }}</option>
                  {% endfor %}
              </select>
            </div>
          </div>
        </form>

Script:
$("#id_region").change(function () {
      var url = $("#search").attr("search");
      var regionId = $(this).val();

      $.ajax({
        url: url,
        data: {
          'region': regionId
        },
        success: function (data) {
          $("#id_city").html(data);
        }
      });
    });

$("#id_city").change(function () {
      var url = $("#search").attr("search");
      var cityId = $(this).val();

      $.ajax({
        url: url,
        data: {
          'city': cityId
        },
        success: function (data) {
          $("#id_district").html(data);
        }
      });
    });

urls.py Maybe you need to make a separate function for the region, city and district, but then in the template how to do it right? I need one search button, one search form. In general, at least an example, some, if any, please show, because so far I am new to JS.
path('search', views.search, name='search'),

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question