jeudi 22 juillet 2021

Django - How to group forms.CheckboxSelectMultiple items by unique parent field value?

My category models:

class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)
    description = models.CharField(max_length=255, default='')

    def __str__(self):
        return "%s" % (self.name)


class SubCategory(models.Model):
    name = models.CharField(max_length=50, unique=True)
    description = models.CharField(max_length=255, default='')
    category = models.ForeignKey(Category, on_delete=models.CASCADE)


    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']

Here's my Job class:

class Job(models.Model):
    ...
    skill_set = models.ManyToManyField(SubCategory)

my forms.py:

class CustomSelectMultiple(ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "%s - %s" %(obj.category, obj.name)
        # return "%s" %(obj.name)

class NewJobForm(forms.ModelForm):
    
    skill_set = CustomSelectMultiple(widget=forms.CheckboxSelectMultiple, queryset=SubCategory.objects.all())
    
    class Meta:
            model = Job
            fields = ['skill_set']

In my template file I have a standard:


In my context:

form = NewJobForm()

So as expected in my form I see:

enter image description here

But I would like my checkboxes to be display as such:

enter image description here

How can I achieve that?




Aucun commentaire:

Enregistrer un commentaire