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.