Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ModelChoiceField with instant filtered options

I'm making one app with 3 classes: emploee, company and department.

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

It's is not a question of priviges. For the validation of the department field, it needs to be a department from the company selected. But, I don't want to make a validation for this, I need to only show the departments from a specific company selected in the field above.

As it is a client side operation I think javascript will be needed, so I wanna know if it is automated in some way in django or I need to download a django-plugin or jquery-plugin for this purpose.

I appreciate any help, thanks!

like image 958
staticdev Avatar asked Nov 25 '25 20:11

staticdev


1 Answers

It is not a built in thing for django and will require a little bit of hacking, but I have done this kind of thing before.

You will want to attach a jQuery AJAX request to an onChange event for company select field. When someone selects a company you query the database and ask for a list of departments that are specific 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')
like image 167
Dominic Santos Avatar answered Nov 28 '25 09:11

Dominic Santos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!