MU
Maciej UrmańskiAug. 28, 2021, 6:06 a.m.

Django template forloop counter change design after x article

Django, django

Hi, I try to achieve something like this:

But my code doesnt work. I mean, work, but elements just show as broken like this:

My code:

<div class="trending position-relative pb-65">
  <div class="container">
      <div class="row">
        {% for article in healtharticles %}

        <div class="col-lg-4 col-md-12 mb-4 mb-lg-0">
            <!-- News block -->
            {% if forloop.first %}
            <div>

              <!-- Featured image -->
              <div class="bg-image hover-overlay shadow-1-strong ripple rounded-5 mb-4" data-mdb-ripple-color="light">
                <img src="https://mdbootstrap.com/img/new/fluid/city/113.jpg" class="img-fluid" />
                <a href="#!">
                  <div class="mask" style="background-color: rgba(251, 251, 251, 0.15);"></div>
                </a>
              </div>

              <!-- Article data -->
              <div class="row mb-3">
                <div class="col-6">
                  <a href="" class="text-info">
                    <i class="fas fa-plane"></i>
                    Travels
                  </a>
                </div>

                <div class="col-6 text-end">
                  <u> 15.07.2020</u>
                </div>
              </div>

              <!-- Article title and description -->
              <a href="" class="text-dark">
                <h5>This is title of the news</h5>

                <p>
                  Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, iste aliquid. Sed
                  id nihil magni, sint vero provident esse numquam perferendis ducimus dicta
                  adipisci iusto nam temporibus modi animi laboriosam?
                </p>
              </a>
              {% else %}
              <hr />

              <!-- News -->
              <a href="" class="text-dark">
                <div class="row mb-4 border-bottom pb-2">
                  <div class="col-3">
                    <img src="https://mdbootstrap.com/img/new/standard/city/041.jpg"
                         class="img-fluid shadow-1-strong rounded" alt="" />
                  </div>

                  <div class="col-9">
                    <p class="mb-2"><strong>Lorem ipsum dolor sit amet</strong></p>
                    <p>
                      <u> 15.07.2020</u>
                    </p>
                  </div>
                </div>
              </a>
              {% endif %}

            </div>

            <!-- News block -->
          </div>


        {% endfor %}
      </div>
  </div>
</div>

Maybe You have idea how to do this corectly.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

1
Илья Чичак
  • Aug. 30, 2021, 7:46 a.m.

Hi!
You've got an error in markup
the first div after {% if forloop.first %} is closing after {% endif %}. You should put openning div outside of forloop or make in every if-branch. (I prefer the second way)
so, you can try this:

<div class="trending position-relative pb-65">
    <div class="container">
        <div class="row">
            {% for article in healtharticles %}

            <div class="col-lg-4 col-md-12 mb-4 mb-lg-0">
                <!-- News block -->
                {% if forloop.first %}
                <div>

                    <!-- Featured image -->
                    <div class="bg-image hover-overlay shadow-1-strong ripple rounded-5 mb-4"
                        data-mdb-ripple-color="light">
                        <img src="https://mdbootstrap.com/img/new/fluid/city/113.jpg" class="img-fluid" />
                        <a href="#!">
                            <div class="mask" style="background-color: rgba(251, 251, 251, 0.15);"></div>
                        </a>
                    </div>

                    <!-- Article data -->
                    <div class="row mb-3">
                        <div class="col-6">
                            <a href="" class="text-info">
                                <i class="fas fa-plane"></i>
                                Travels
                            </a>
                        </div>

                        <div class="col-6 text-end">
                            <u> 15.07.2020</u>
                        </div>
                    </div>

                    <!-- Article title and description -->
                    <a href="" class="text-dark">
                        <h5>This is title of the news</h5>

                        <p>
                            Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, iste aliquid. Sed
                            id nihil magni, sint vero provident esse numquam perferendis ducimus dicta
                            adipisci iusto nam temporibus modi animi laboriosam?
                        </p>
                    </a>
                </div>

                {% else %}
                <hr />
                <div>

                    <!-- News -->
                    <a href="" class="text-dark">
                        <div class="row mb-4 border-bottom pb-2">
                            <div class="col-3">
                                <img src="https://mdbootstrap.com/img/new/standard/city/041.jpg"
                                    class="img-fluid shadow-1-strong rounded" alt="" />
                            </div>

                            <div class="col-9">
                                <p class="mb-2"><strong>Lorem ipsum dolor sit amet</strong></p>
                                <p>
                                    <u> 15.07.2020</u>
                                </p>
                            </div>
                        </div>
                    </a>
                </div>
                {% endif %}
                <!-- News block -->
            </div>
            {% endfor %}
        </div>
    </div>
</div>

    Comments

    Only authorized users can post comments.
    Please, Log in or Sign up
    MB

    Qt - Test 001. Signals and slots

    • Result:57points,
    • Rating points-2
    MB

    C++ - Test 001. The first program and data types

    • Result:60points,
    • Rating points-1
    GK

    C++ - Test 005. Structures and Classes

    • Result:0points,
    • Rating points-10
    Last comments
    J
    JonnyJoJune 8, 2023, 12:14 p.m.
    Qt/C++ - Lesson 019. How to paint triangle in Qt5. Positioning shapes in QGraphicsScene Евгений, здравствуйте! Решил поэкспериментировать немного с кодом из этого урока, нарисовать вместо треугольника квадрат и разобраться с координатами. В итоге, запутался. И ни документация,…
    J
    JonnyJoMay 25, 2023, 2:24 p.m.
    How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
    Evgenii Legotckoi
    Evgenii LegotckoiMay 25, 2023, 4:49 a.m.
    How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
    J
    JonnyJoMay 21, 2023, 10:49 a.m.
    How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
    Evgenii Legotckoi
    Evgenii LegotckoiMay 21, 2023, 5:57 a.m.
    How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
    Now discuss on the forum
    T
    TwangerJune 7, 2023, 11:12 a.m.
    Ошибка при выполнении триггерной функции (GreenPlum) Есть 3 таблицы fact_amount со структурой: CREATE TABLE fact_amount ( id serial4 NOT NULL, fdate date NULL, type_activity_id int4 NULL, status_id int4 NULL, CONSTRAINT fact…
    AR
    Alexander RyabikovJune 6, 2023, 1:35 p.m.
    Работа с QFileSystemModel Вопросик по теме QFileSystemModel в Linux. Он, как и положено, обновляется самостоятельно, если директория локальная. Но, вот, сетевая папка (у меня шара samba) не обновляется. Как её можно…
    Evgenii Legotckoi
    Evgenii LegotckoiApril 16, 2023, 4:07 a.m.
    Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
    АБ
    Алексей БобровDec. 14, 2021, 7:03 p.m.
    Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

    Follow us in social networks