[Fixed]-Dependencies betwee fields in Django form

1👍

Ajax/jQuery solution:

  1. use jQuery (include jQuery file to your template, for example call it from CDN) at the end of your template to make ajax get request after category is selected
    • when template will load the subcategory field will be cleared and Select category option will be prepended to it
    • when category will be selected change function will trigger ajax GET request on request_url
    • the selected category (category_id) will be passed to url and than to view (see point 3. to get the idea what happend after view runs)
<script type='text/javascript'>
$(function(){
  $('select[name=subcategory]').empty();
  $('select[name=subcategory]').prepend('<option value="Not selected" selected disabled>Select Category...</option>');
  // called when category field changes from initial value
  $('select[name=massage]').change(function(){
    if($("#id_category option:selected").text()) != (YOU SHOULD INSERT THE INITIAL VALUE OF THE CATEGORY FIELD WHEN IT IS NOT SELECTED) {
    category_id = $('select[name=category]').val();
    request_url = '/get_subcategory/' + category_id + '/';
      $.ajax({
        url: request_url,
        type: "GET",
        success: function(data){
          $.each(data, function(key, value){
            $('select[name=subcategory]').empty();
            $('select[name=subcategory]').append('<option value="' + key + '">' + value + '</option>');
          });
        }
      })
    }
  })
});
</script>
  1. create appropriate url in urls.py that will handle the get request from ajax in jQuery, when category is selected:

in urls.py file:

url(r'^get_subcategory/(?P<category_id>[0-9]+)/$', views.get_subcategory, name='get_subcategory'),
  1. now create the appropriate view in views.py that will run after get request at previous url:
    • subcategories that are linked to selected category (identified by category_id) will be filtered and sent back to template
    • in ajax success function (see point 1.) the subcategory dropdown menu will be populated with filtered subcategories

in views.py file:

import json

def get_subcategory(request, category_id):
    category = Category.objects.get(pk=category_id)
    subcategories = category.subcategory_set.all()
    subcategories_dict = {}
    for subcategory in subcategories:
    // if your subcategory has field name
    subcategories_dict[subcategory.id] = subcategory.name
    return HttpResponse(json.dumps(subcategories_dict), content_type="application/json")

Leave a comment