Filter foreignkey field from the selection of another foreignkey in django-admin?
i have the next models
class Region(models.Model):
nombre = models.CharField(max_length=25)
class D开发者_StackOverflow中文版epartamento(models.Model):
nombre = models.CharField(max_length=25)
region = models.ForeignKey(Region)
class Municipio(models.Model):
nombre = models.CharField(max_length=35)
departamento = models.ForeignKey(Departamento)
i need to filter the options in Departamento according selected Region, and filter the options in Municipio according selected Departamento.
is that possible??
Thanks folks!
Assuming you are talking about doing this in a series of select boxes:
Create two views, one which returns a response containing the Departamentos for a given Region. The other does the same but for Municipios in a Departamento
# views.py
from django.core import serializers
def departamentos_por_region(request, region_id):
region = get_object_or_404(Region, id=region_id)
departamentos = Departamento.objects.filter(region=region)
return render_to_reponse("format_as_option_list.html",
{'departamentos': departamentos})
def municipios_por_departamento(request, departamento_id):
# basically the same as above
I'm assuming that you're filling the Region select box in the initial page view, so no special view needed there.
The template should format the departamentos as an html option list.
Assuming then that the HTML in the initial page view looks something like:
<select id='regions'>
<option value='1'>Region 1</option>
<option value='2'>Region 2</option>
</select>
<select id='departamentos'>
</select>
<select id='municipios'>
</select>
You'd use some javascript like (in jQuery):
// this isn't tested code and likely contains an error or two
$('#regions').change(function(){
// Region has changed, so reset Departamentos and Municipios
$('#departamentos').html("")
$('#municipios').html("")
// now update the departamentos
$.get('/ajax/departamentos_por_region/' + $('#regions').val(),
function(data) {
('#departamentos').html(data)
};
);
});
Do the same for Municipios as for Departamentos.
You'd probably also want to do things like disable fields when they have no available choices, and handle cases where no departamentos or municipios are returned.
精彩评论