MPTT 多个 parents 面包屑导航

MPTT multiple parents breadcrumbs

假设我有一个简单的模型集:

class Category(MPTTModel):
    name = CharField(max_length=50)
    parent = TreeForeignKey(
        'self',
        null=True,
        blank=True,
        related_name='children',
        db_index=True
    )

class Record(Model):
    name = CharField(max_length=50)
    category = TreeManyToManyField(SectionArt)

让我们假设我有一个属于 3 个不同类别的 Record。如何使面包屑跟踪我打开记录的类别?

您可以使用 request.META['HTTP_REFERER']

跟踪用户来自何处

views.py

def get_context_data(self, **kwargs):
    c = super(RecordDetail, self).get_context_data(**kwargs)
    if 'HTTP_REFERER' in self.request.META:
        referer = self.request.META['HTTP_REFERER'].split('/')[-2]
        c['categories'] = [models.Category.objects.get(slug=referer)]
    else:
        c['categories'] = self.object.categories.all()
    return c

template.html

<ul class="breadcrumbs">
    <li><a href="{{ sections.home.get_absolute_url }}">{{ sections.home.title }}</a></li>
    {% if categories %}
        {% with category=categories.0 %}
            {% for obj in category.get_ancestors %}
                <li><a href="{{ obj.get_absolute_url }}">{{ obj.title }}</a></li>
            {% endfor %}
            <li><a href="{{ category.get_absolute_url }}">{{ category.title }}</a></li>
        {% endwith %}
    {% endif %}
    <li class="current">{{ object.short_title }}</li>
</ul>

Source