2👍
✅
You achieve this using jQuery and Ajax. Try using the following:
project_change.js
(function($){
$(function(){
$(document).ready(function() {
$('#id_Project').bind('change', project_change);
$('#id_Milestone > option').show();
if ($('#id_Project').val() != '') {
var project_id = $('#id_Project').val();
$.ajax({
"type" : "GET",
"url" : "/product_change/?project_id="+project_id,
"dataType" : "json",
"cache" : false,
"success" : function(json) {
$('#id_Milestone >option').remove();
for(var j = 0; j < json.length; j++){
$('#id_Milestone').append($('<option></option>').val(json[j][0]).html(json[j][1]));
}
}
});
}
});
});
})(django.jQuery);
// based on the project, milestone will be loaded
var $ = django.jQuery.noConflict();
function project_change()
{
var project_id = $('#id_Project').val();
$.ajax({
"type" : "GET",
"url" : "/product_change/?project_id="+project_id,
"dataType" : "json",
"cache" : false,
"success" : function(json) {
$('#id_Milestone > option').remove();
for(var j = 0; j < json.length; j++){
$('#id_Milestone').append($('<option></option>').val(json[j][0]).html(json[j][1]));
}
}
})(jQuery);
}
Include the following in views.py:
from django.shortcuts import HttpResponse
from django.utils import simplejson
from ticket.models import Milestone
def project_choices(request):
milestone_list = []
project_id = request.GET.get('project_id')
milestones = Milestone.objects.filter(project = project_id)
[milestone_list.append((each_milestone.pk,each_milestone.name)) for each_milestone in milestones]
json = simplejson.dumps(milestone_list)
return HttpResponse(json, mimetype='application/javascript')
In urls.py:
from ticket.views import project_choices
urlpatterns = patterns(
(r'^product_change/', project_choices),
)
In admin.py where you want to load milestone based on project:
class Media:
js = ['/path/to/project_change.js',]
I hope this will help you.
0👍
You can also use django dynamic choices for this
It implements something similar to arulmr’s answer but in a generic way where you can set up the mappings in django code. There isn’t any documentation but the project has good unit tests and is written by a django core developer.
👤sef
Source:stackexchange.com