Answer the question
In order to leave comments, you need to log in
How to display subcategories in Django?
Good afternoon, tell me how, when choosing a category, to get the following subcategories, it didn’t work with ajax before, and I’m new to django.
class StudentClass(models.Model):
"""Группы"""
city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True, null=False, verbose_name="Город")
branch = models.ForeignKey(Branch, on_delete=models.CASCADE, blank=True, null=False, verbose_name="Филиал")
teatcher = models.ForeignKey('staffs.Staff', on_delete=models.CASCADE, blank=True, null=False, verbose_name="Преподаватель")
name = models.CharField("Название", max_length=200, unique=True)
class Meta:
verbose_name = "Class"
verbose_name_plural = "Classes"
ordering = ["name"]
def __str__(self):
return self.name
class City(models.Model):
"""Города"""
name = models.CharField("Название", max_length=200, unique=True)
supervisor = models.ForeignKey(
'staffs.Staff', related_name="staffcity", on_delete=models.CASCADE, blank=True, null=True, verbose_name='Руководитель'
)
class Meta:
ordering = ["name", "supervisor"]
verbose_name = 'city'
verbose_name_plural = 'cities'
def __str__(self):
return self.name
class Branch(models.Model):
"""Филиалы"""
city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True, null=False, verbose_name="Город")
address = models.CharField("Адрес", max_length=250, unique=False)
title = models.CharField("Название", max_length=100, unique=False)
class Meta:
ordering = ["city", "title"]
verbose_name = 'branch'
verbose_name_plural = 'branches'
def __str__(self):
return self.title
def get_branch(request):
id = request.GET.get('id', '')
result = list(Branch.objects.filter(
city_id=int(id)).values('id', 'title'))
return HttpResponse(json.dumps(result), content_type="application/json")
url(r'^/get_branch/$', get_branch),
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(document).on("change", "select#id_Class-city", function () {
$.getJSON("/get_branch/", { id: $(this).val() }, function (j) {
let options = '<option value="">---------</option>';
for (let i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + "</option>";
}
$("select#id_Class-branch").html(options);
});
});
});
</script>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question