Django ModelChoiceField with Instant Filtering Options

I am making one application with 3 classes: emploee, company and department.

When I edit emploee, I need to know his company, and then have a field with all departments of the selected company. But when I use ModelChoiceField, I see all departments from all companies.

This is not a question of rest. To check the department’s field, you must be the department of the selected company. But I do not want to do validation for this, I need to show only departments from a particular company selected in the field above.

How it works on the client side, I think javascript will be needed, so I want to know if it is somehow automated in django, or if I need to download a django-plugin or jquery-plugin for this purpose.

I appreciate any help, thanks!

+3
source share
1 answer

This is not a built-in thing for django and will require a bit of hacking, but I have already done this before.

You will want to attach the jQuery AJAX request to the onChange event for the company selection field. When someone selects a company, you request a database and request a list of departments that relate to that company.

EDIT:

Something like the following javascript and django will work:

$('#id_company').change(function(){
  $.POST('{% url some_url_name %}',
    {
      'company_id': $('#id_company').val()
    },
    function(data){
      if(data.valid){
        var d = '<select id="id_department" name="department">';
        $.each(data.records, function(k,v){
          d += '<option value="' + v.id + '">' + v.name +'</option>';
        });
        d += '</select>';
        $('#id_department').html(d);
      }
    }, 'json'
  );
});


def ajax_request(request, company_id):
  if request.is_ajax() and request.method == 'POST':
    data = simplejson.dumps(Department.objects.filter(company__id=company_id)
    return HttpResponse(data, mimetype='application/javascript')
+4
source

All Articles