Answer the question
In order to leave comments, you need to log in
Django MPTT: How to automatically select children in a tree when a parent is selected?
When selecting a parent ( Cluster #1
), children ( Store #1
and Store #2
) are not selected:
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
from django.contrib import admin
from deviations.forms import MyForm
from deviations.models import Deviation
@admin.register(Deviation)
class DeviationAdmin(admin.ModelAdmin):
form = MyForm
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 questionAsk a Question
731 491 924 answers to any question