开发者

Django ModelChoiceField with instant filtered options

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

When I edit an emp开发者_运维问答loee 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!


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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜