0

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.

user3422616
  • 23
  • 1
  • 5

2 Answers2

0

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

0
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)
x-king
  • 1
  • 2
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Apr 10 '20 at 18:13