Search code examples
pythonpython-3.xdjangodjango-mptt

How to fix no of child to parent in django-mptt?


I'm want to fix 2 children for each parent.

Models.py

class CoachingRegistration(MPTTModel):
    uid = models.UUIDField(unique=True, editable=False, default=uuid.uuid4)
    placement_id = models.CharField(max_length=13)

    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['placement_id']

    def __str__(self):
        return str(self.placement_id) 

Please help me how to fix this.


Solution

  • You can fix this in createview with form form_valid function

    class CoachingRegistrationCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView):
        model = CoachingRegistration
        form_class = CoachingRegistrationForm
        template_name = 'customer/form_coaching_register.html'
    
        def form_valid(self, form):
            if 2 > CoachingRegistration.objects.filter(parent=CoachingRegistration.objects.get(coaching_id=form.instance.placement_id)).count():
                return super().form_valid(form)
            else:
                return super().form_invalid(form)