O
O
Oleg Seledets2022-02-10 23:51:03
AJAX
Oleg Seledets, 2022-02-10 23:51:03

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.

Screenshot
620578928865c790169590.png

When choosing a city, it is necessary that branches related to this city appear.
Models-StudentClass
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

model City

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


models Branch

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


In views added the function of getting a branch
views get_branch

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")


in urls
URLs

url(r'^/get_branch/$', get_branch),

Based on the prompts, I took and modified the request
ajax request

<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>


This request was placed in the html form responsible for adding data to the "Groups"
But nothing has changed, what did I do wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question