Django nested if statement giving me a strange error

Viewed 205

I have 2 if statements right next to each other to check for to see if a user is following another user. I am getting a weird error when I attempt to close both of the if statements. I have a block content and endblock at the top and bottom of the page. I also have a load humanize tag. I have attempted to add a endblock tag and I tried reshuffling things around. I am kinda stuck but I know I'm forgetting something. Can any help me out?

Here is the code

{% extends 'core/base.html' %} {% load humanize %} {% block content %}
<div class="container">
  <div class="columns">
    <div class="column is-12">
      <h1 class="title">{{ request.user.username }}</h1>
      <p>Followers: {{ user.foxyprofile.followed_by.count }}</p>
      <p>Follows {{ user.foxyprofile.follows.count }}</p>
      {% if user != request.user %} {% if request.user.foxyprofile in
      user.foxyprofile.followed_by.all %}
      <a href="{% url 'unfollow_foxy' user.username %}" class="button is-danger"
        >Unfollow</a
      >
      {% else %}
      <a href="{% url 'follow_foxy' user.username %}" class="button is-success"
        >Follow {{ user.username}}</a
      >
      {% endif %} {% endif %}
    </div>
  </div>
  <div class="columns">
    <div class="column is-8">
      <div class="wrapper-fox">
        {% for fox in user.foxs.all %}
        <div class="fox">
          <p class="name">{{ fox.created_by.username }}</p>
          <p>{{ fox.body }}</p>
          <p class="info">{{ fox.created_at|naturaltime}}</p>
          <hr />
          {% endfor %}
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

and the error I'm getting...

Invalid block tag on line 17: 'endif', expected 'endblock'. Did you forget to register or load this tag?

1 Answers

You should not add a line break in the second if statement, a tag is fully specified on a single line. This thus means that the {% if … %} tags [Django-doc] look like:

{% if user != request.user %}
    {% if request.user.foxyprofile in user.foxyprofile.followed_by.all %}
        …
    {% else %}
        …
    {% endif %}
{% endif %}

or you put the two {% if … %} tags on the same line:

{% if user != request.user %}{% if request.user.foxyprofile in user.foxyprofile.followed_by.all %}
        …
{% else %}
        …
{% endif %}{% endif %}

You can also write the {% if … %}s on two lines and the two {% endif %} on the same line. The only thing that is not allowed is splitting a tag over multiple lines in the template file.

In Django the template parser can not handle template tags on multiple lines, or at least not at the time of writing.

Related