Home > OS >  Django Template tag in {% if %} block does not show
Django Template tag in {% if %} block does not show

Time:11-09

I'm making a bulletin board with Django.

How can I express it with the letters I want instead of the type number? my bulletin board

HTML template(board.html)

{% for p in postlist %}
    <tr>
        <td>
            {% if p.p_type == '1' %}
            'cloud'
            {% elif p.p_type == '2' %}
            'wind'
            {% endif %}
        </td>
    </tr>
{% endfor %}

output

(EMPTY)

expected

cloud wind

Vies.py

def board(request, p_type=None):
    current_type = None
    p_types = PostType.objects.all()
    postlist = Post.objects.all()

    page = request.GET.get('page', '1')
    if p_type:
        current_type = get_object_or_404(PostType, p_type=p_type)
        postlist = postlist.filter(p_type=current_type)

    paginator = Paginator(postlist, 10)  # Showing 20 posts.
    page_obj = paginator.get_page(page)

    return render(request, 'board/board.html', {'current_type':current_type, 'p_types': p_types, 'postlist': page_obj})

Model.py

class PostType(models.Model):
p_type = models.CharField(max_length=200, db_index=True)

def __str__(self):
    return self.p_type

def get_ptype_url(self):
    return reverse('board:board', args=[self.p_type])

CodePudding user response:

try this.In django when you create a foreignkey it will add _id to it for the database so now inside your template you can compare it using this id(p_type_id) and you should be sure that Cloud has pk=1 and Wind has a pk=2.

{% for p in postlist %}
    <tr>
        <td>
            {% if p.p_type_id == 1 %}
                'cloud'
                {% elif p.p_type_id == 2 %}
                'wind'
                {% endif %}
            </td>
        </tr>
    {% endfor %}
  • Related