Django Template не работает с циклом for в диапазоне. Почему?
VIEWS.PY
def index(request):
posts = Post.objects.all()
posts_quantity = range(1)
return render(request, 'index.html', {'posts':posts, 'posts_quantity':posts_quantity})
HTML
{% for index in posts_quantity %}
<a href = "{% url 'architectural_post' posts.index.slug %}" class = "post">
{% endfor %}
выдает ошибку: Reverse for 'architectural_post' with arguments '('',)' not found.
Но все работает хорошо, если я ставлю 0 вместо index, вот так (просто для отладки):
{% for index in posts_quantity %}
<a href = "{% url 'architectural_post' posts.0.slug %}" class = "post">
{% endfor %}
Почему и как это исправить? Спасибо.
Ошибка возникает из-за того, что переменной posts.index.slug
передается неправильное значение. Поскольку вы используете range(1) для перебора posts_quantity
, переменной index на каждой итерации присваивается значение 0. Поэтому в теге url следует использовать posts.0.slug
вместо posts.index.slug
.
Чтобы исправить эту проблему, вы можете изменить код на:
{% for index in posts_quantity %}
<a href = "{% url 'architectural_post' posts.index.slug %}" class = "post">
{% endfor %}
to
{% for index in range %}
<a href = "{% url 'architectural_post' posts.index.slug %}" class = "post">
{% endfor %}
Вам следует изменить переменную posts_quantity
на range(len(posts))
и изменить цикл for на for index in range(len(posts))
Это должно исправить проблему и правильно передать значение slug в URL архитектурного_поста.
Django не интерпретирует posts.index.slug
как posts.0.slug
. Вместо этого, Django пытается найти атрибут под названием index
на объекте posts
.
Это не очень интуитивно, но так оно и есть.
Вы можете исправить это, выполнив итерацию над posts
непосредственно:
{% for post in posts %}
<a href="{% url 'architectural_post' post.slug %}" class="post">
{% endfor %}