First, allow me to introduce myself, I’m the owner of a small software house whose working mainly with Django as backend since 2017 but until today we didn’t felt the need to ask for help thanks to the framework ease of use.
Second, I know in internet there are other post on topic, but until now none of the solutions found worked for me… hence here I am kindly asking your help.
The task is simple: in Django Admin I have a form with a drop-down menu whose select must filter and fill-in another drop-down menu.
At first attempt I tried to simply add a jQuery to my form to get the changes on field select. The .js is correctly loaded together with other Javascripts but simply nothing happen when I made a selection on the parent drop-down.
At second attempt, I tried to add the widget on form declaration. Same result as above.
Following is my last attempt, result as above:
Models.py
class Utenti(models.Model):
nome = models.CharField(max_length = 188)
cognome = models.CharField(max_length = 188)
dataNascita = models.DateField(max_length = 8, verbose_name = "Data di nascita")
genere = models.CharField(max_length = 19, choices = generi, null = True, blank = True, verbose_name = "Genere")
provincia = models.ForeignKey(Provincia, on_delete = models.SET_NULL, null = True)
citta = models.ForeignKey(Comune, on_delete = models.SET_NULL, null = True, verbose_name = "Citta'")
cf = models.CharField(max_length = 16, validators = [ validate_codice_fiscale ])
class Meta:
verbose_name = "Utente"
verbose_name_plural = "Utenti"
def __str__(self):
return str(self.nome) + " " + str(self.cognome)
Admin.py
class FormUtenti(forms.ModelForm):
class Meta:
model = Utenti
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
province = [('','---------')] + [(i.codice_provincia, i.name) for i in Provincia.objects.all()]
self.fields['citta'].queryset = Comune.objects.none()
self.fields['provincia'].widget = forms.Select(
attrs = {
'onchange': 'filterCities(this.value);',
},
choices = province
)
class UtentiAdmin(admin.ModelAdmin):
form = FormUtenti
class Media:
js = (
'admin/js/jquery.init.js', // to verify script not launched before jQuery init
'admin/js/getCities.js',
)
getCities.js
'use strict';
{
const $ = django.jQuery;
function filterCities(provincia_id){
$.ajax({
url:"/get_cities/",
type:"POST",
data:{provincia: provincia_id,},
success: function(result) {
this.alert(result);
cls = document.getElementById("id_citta_select");
cls.options.length = 0;
for(var item in result) {
cls.options.add(new Option(item, result[item]));
}
},
error: function(e) {
alert(JSON.stringify(e));
},
});
}
}
views.py
def get_cities(request):
test_request_log = TestRequestLog(test_request_message= request)
test_request_log.save()
provincia_id = request.POST.get('provincia')
citta = Comune.objects.filter(provincia_id = provincia_id).order_by('name')
return JsonResponse({
"data": [{'citta': c.name} for c in citta],
})
urls.py
path('get_cities/', views.get_cities, name='get_cities'),
I’m pretty sure the code don’t go beyond the Javascript, otherwise I should see the ajax call somewehere and definetely the request in the test log (request btw I manually tested with success).
Any fresh idea?
Thank you