X
X
xxx2018-09-01 23:25:21
Django
xxx, 2018-09-01 23:25:21

Nested django menu?

I'm trying to make a nested menu in the admin panel. Via FKself.
models.py

class Category(models.Model):
  parent = models.ForeignKey(
    'self',
    default=None,
    blank=True, null=True,
    on_delete=models.CASCADE,
    related_name='parent_%(class)s',
    verbose_name='parent comment'
  )
  name = models.CharField('Категория',max_length=20)
  slug = models.SlugField('Текст в url', max_length=200, unique=True)
  class Meta:
    ordering = ['name']
    verbose_name = 'Категория'
    verbose_name_plural = 'Категории'
  def __str__(self):
    return self.name
  def get_absolute_url(self):
    if self.sex == 'M':
      return reverse('category_for_men', args=[str(self.slug)]) 
    else:
      return reverse('category_for_women', args=[str(self.slug)])

Query
"post_list_for_man": Category.objects.all(),
template
{% for x in post_list_for_man %}
    {% if x.parent %}
    <li class="has-children">
    <a href="{{ x.parent.get_absolute_url }}" title="">{{ x.parent }}</a>
    <ul class="sub-menu">
    <li><a href="{{ x.get_absolute_url }}">{{ x }}</a></li>
    </ul>
    </li>
    {% endif %}
{% endfor %}

And if I add the following.
Category
Subcategory
Second subcategory
Category does not have a parent
Subcategory has a parent Category
Second subcategory has a parent Category

Template gives x.parent2 identical values ​​- Category, you need one, somehow use Distinct.
Well, accordingly, in the drop-down menu of the Category, the subcategories are different.
How to implement this correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-09-02
@Heavy10110

Look at mptt and django-mptt

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question