Echo Foe
Echo Foe

Reputation: 498

Could not find the variable, namely could not find the key "VariableDoesNotExist at /genres/"

I can not get the objects on the template that are associated with the mptt django model. Failed lookup for key [genres]. I have a model that is linked to another model. I use mptt django so that the object is connected through the relationship of many to many. Everything is fine on the administrative panel, but this problem occurs when displaying an object on a template. What should I do best? Maybe I am setting the cycle for the object incorrectly ?

models.py:

from django.db import models
from django.urls import reverse
from django.utils import timezone
from mptt.models import MPTTModel, TreeForeignKey, TreeManyToManyField


class Genre(MPTTModel):
    name = models.CharField(max_length=50, unique=True, verbose_name='Подкатегория')
    slug = models.SlugField(max_length=200, null=True, blank=True, unique=True, verbose_name='Nazvanie_kategorii')
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children',
                            verbose_name='Категория')
    is_active = models.BooleanField(default=False, verbose_name='Активность категории')
    created = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата создания записи')
    updated = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата ред-ия записи')

    class MPTTMeta:
        order_insertion_by = ['name']
        verbose_name = 'Тест мптт'
        verbose_name_plural = 'Тест мптт'

    class Meta:
        verbose_name = 'Дерево категорий'
        verbose_name_plural = 'Дерево категорий'

    def __str__(self):
        return '%s' % self.name

    def get_absolute_url(self):
        return reverse('test_mptt:promotion_list_by_category', args=[self.slug])

views.py:

from django.shortcuts import render, get_object_or_404
from .models import Genre, Promotion, PromotionDetails
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def show_genres(request, category_slug=None):
    category = None
    categories = Genre.objects.all()
    promotions = Promotion.objects.filter(is_active=True)
    if category_slug:
        category = get_object_or_404(Genre, slug=category_slug)
        promotions = promotions.filter(category=category)
    return render(request, "genre/list.html", {'category': category,
                                               'categories': categories,
                                               'promotions': promotions})

html template list.html:(I have imported {% load mptt_tags %})

<div class="latest_product_inner row">
    {% for promotion in promotions %}
        <div class="col-md-12">
            <div class="offer_post">
                <div class="offer_details">
                    {% if promotion.site %}
                    <a href="{{ promotion.site }}" target="_blank"><h2>{{ promotion.name }}</h2></a>
                    {% else %}
                    <a><h2>{{ promotion.name }}</h2></a>
                    {% endif %}
                    <p>{{promotion.description|truncatechars:220}}</p>
                    <div class="offer_info text-left">
                        <div class="offer_tag">
                            <a class="active" href="#">{{ promotion.category }}</a>
                        </div>
                        <ul class="offer_meta list">
                            <li><a href="/"><i class="lnr lnr-home"></i> Адрес: {{ promotion.country }}, {{ promotion.region }}, {{ promotion.town }}, {{ promotion.address }}</a></li>
                            {% if promotion.schedule_start and promotion.schedule_end %}
                            <li><a><i class="lnr lnr-clock"></i> Часы работы: {{ promotion.schedule_start|time:'H:i' }} - {{ promotion.schedule_end|time:'H:i' }}</a></li>
                            {% else %}
                            <li><a><i class="lnr lnr-calendar-full"></i> Часы работы: круглосуточно </a></li>
                            {% endif %}
                            {% if promotion.phone %}
                            <li><a><i class="lnr lnr-phone"></i> Телеофон: {{ promotion.phone }} </a></li>
                            {% endif %}
                        </ul>
                    </div>
                    <a href="{{ promotion.get_absolute_url }}" class="white_bg_btn">Подробнее</a>
                </div>
            </div>
        </div>
    {% endfor %}
</div>
<aside class="left_widgets cat_widgets">
    <div class="widgets_inner">
        <ul class="list">
            {% recursetree genres %}
                <li>
                    <a href="{{ node.get_absolute_url }}">{{ node.name }}</a>
                    {% if not node.is_leaf_node %}
                        <ul class="list">
                            <li><a href="#">{{ children }}</a></li>
                        </ul>
                    {% endif %}
                </li>
            {% endrecursetree %}
        </ul>
    </div>
</aside>

Error log: enter image description here

Upvotes: 0

Views: 164

Answers (1)

John Gordon
John Gordon

Reputation: 33352

The html template contains this line:

{% recursetree genres %}

So the template is expecting to see a variable named genres.

In the view function you have this render call:

return render(request, "genre/list.html", {'category': category,
                                           'categories': categories,
                                           'promotions': promotions})

You are not passing a variable named genres to the template.

Upvotes: 2

Related Questions