A
A
albertalexandrov2021-09-01 21:19:31
Django
albertalexandrov, 2021-09-01 21:19:31

Django MPTT: How to automatically select children in a tree when a parent is selected?

When selecting a parent ( Cluster #1), children ( Store #1and Store #2) are not selected:

612fc30ec5d14177202084.png

How can I make sure that when a parent is selected, all descendants are automatically selected?

Models

from django.db import models
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModel


class Orgunit(MPTTModel):
    name = models.CharField(
        max_length=100
    )
    type = models.CharField(
        choices=[
            ('MACRO', 'Макро'),
            ('CLUSTER', 'Кластер'),
            ('KUST', 'Куст'),
            ('STORE', 'Магазин')
        ],
        max_length=100
    )
    parent = TreeForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='children'
    )

    def __str__(self):
        return self.name


class Deviation(models.Model):
    name = models.CharField(max_length=100)
    number = models.PositiveIntegerField(null=True)
    orgunits = models.ManyToManyField('orgunits.Orgunit')

    def __str__(self):
        return self.name


Admin:

from django.contrib import admin

from deviations.forms import MyForm
from deviations.models import Deviation


@admin.register(Deviation)
class DeviationAdmin(admin.ModelAdmin):
    form = MyForm


The form:

from django.forms import ModelForm, widgets
from mptt.forms import TreeNodeMultipleChoiceField

from orgunits.models import Orgunit


class MyForm(ModelForm):
    orgunits = TreeNodeMultipleChoiceField(queryset=Orgunit.objects.all(), widget=widgets.SelectMultiple())

    class Meta:
        model = Orgunit
        fields = '__all__'

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