1

Let's say I have a simple model set:

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)

And let's imagine I have a Record that belongs to 3 different categories. How do I make breadcrumbs track from which category I opened my record?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Viktor
  • 4,218
  • 4
  • 32
  • 63

1 Answers1

0

You can track where user came from with 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

Community
  • 1
  • 1
Viktor
  • 4,218
  • 4
  • 32
  • 63