I have some troubles when selecting parent - children are not auto selected. For example when I select Cluster #2
its children (Store #1
and Store #2
) are not being selected:
How can I fix that?
It's important because I need to create many-to-many (Deviation-Orgunit) links only with stores
(with leafs).
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
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__'