Django select2, show subcategories when parent category name searched

316 Views Asked by At

I used django-select2 to show parent categories and sub categories. When I search the name of parent category using 'Select2MultipleWidget' (Pacific Time Zone, for example), it does not show its sub categories. Is it possible to show belonging sub categories when parent categories are searched?

I was reading select2 documentation but I couldn't find relevant options.

#models.py
class Category(models.Model):
name = models.CharField(max_length=200)

class SubCategory(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=180)

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user")
    title = models.CharField(max_length=200)
    category = models.ManyToManyField(SubCategory)
    desc = models.TextField()

#forms.py
class PostForm(forms.ModelForm):
def categories_as_choices():
    categories = []
    for category in Category.objects.all():
        new_category = []
        sub_categories = []
        for sub_category in category.subcategory_set.all():
            sub_categories.append([sub_category.id, sub_category.name])

        new_category = [category.name, sub_categories]
        categories.append(new_category)

    return categories

category = forms.ChoiceField(
    choices=categories_as_choices(),
    widget = Select2MultipleWidget(
        attrs={'class': 'form-control col-4'}
        ),
)

    class Meta:
    model = Post
    fields = ['title', 'desc', 'category']

I tried to use select2's example of timezone and state name (Pacific Time Zone as a parent category with California as a sub category). When I type 'Pacific Time Zone', it won't show 'California', sub category.

2

There are 2 best solutions below

1
On
class Category( models.Model ):
Title    = models.CharField( max_length=255, blank=True, null=Falsex) 
Catparents = models.ForeignKey('self',limit_choices_to = {'Catparents__isnull': True}, on_delete=models.CASCADE,related_name="parents", default=1, blank=True, null=True)
2
On

i think you must set this def : def__str__(self): ... return self.any_thing_you_want_to_show in you modelsclass