I have the following models:
class Category(models.Model):
name = models.CharField(max_length=40)
class Item(models.Model):
name = models.CharField(
Here is some javascript (JQuery based) to change the item option values when category changes:
<script charset="utf-8" type="text/javascript">
$(function(){
$("select#id_category").change(function(){
$.getJSON("/items/",{id: $(this).val(), view: 'json'}, function(j) {
var options = '<option value="">-------- </option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("#id_item").html(options);
$("#id_item option:first").attr('selected', 'selected');
})
$("#id_category").attr('selected', 'selected');
})
})
</script>
You need a view to be called on the /items/ URL that supplies a JSON list of the valid items.
You can hook this into your admin by using model admin media definitions.
There is django-smart-selects:
If you have the following model:
class Location(models.Model)
continent = models.ForeignKey(Continent)
country = models.ForeignKey(Country)
area = models.ForeignKey(Area)
city = models.CharField(max_length=50)
street = models.CharField(max_length=100)
And you want that if you select a continent only the countries are available that are located on this continent and the same for areas you can do the following:
from smart_selects.db_fields import ChainedForeignKey
class Location(models.Model)
continent = models.ForeignKey(Continent)
country = ChainedForeignKey(
Country,
chained_field="continent",
chained_model_field="continent",
show_all=False,
auto_choose=True
)
area = ChainedForeignKey(Area, chained_field="country", chained_model_field="country")
city = models.CharField(max_length=50)
street = models.CharField(max_length=100)
You will need to have some kind of non-server based mechanism of filtering the objects. Either that, or you can reload the page when the selection is made (which is likely to be done in JavaScript anyway).
Otherwise, there is no way to get the subset of data from the server to the client.