Sunil
Sunil

Reputation: 57

Conditions in IF Statements requires values to be specified explicitly

I have created a template that displays items from a loop, Within the loop there is a condition, but the condition does not work unless specified explicitly.

{% extends 'blog/base.html' %}
{% block content %}

    <h3>{{ user.username }}</h3>

    {% for project in projects %}
        {% if user.username == 'testuser' %}
            <h5>{{ project.title }}</h5>
            <p>{{ project.description }}</p>
            <p>{{ project.objectives }}</p>
            <pre>{{ project.score }}</pre>
            <pre>{{ project.student_id }}</pre>
        {% endif %}
    {% endfor %}

{% endblock content %}

The above code works perfectly and returns the records assigned to the user named testuser.

But if I write the code as below, it skips all records

{% extends 'blog/base.html' %}
{% block content %}

    <h3>{{ user.username }}</h3>

    {% for project in projects %}
        {% if user.username == project.student_id %}
            <h5>{{ project.title }}</h5>
            <p>{{ project.description }}</p>
            <p>{{ project.objectives }}</p>
            <pre>{{ project.score }}</pre>
            <pre>{{ project.student_id }}</pre>
        {% endif %}
    {% endfor %}

{% endblock content %}

I have added the code from the model

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Projects(models.Model):
    title = models.CharField(max_length=150)
    description = models.TextField()
    objectives = models.TextField()
    score = models.IntegerField()
    #file = models.FileField()
    date_posted = models.DateTimeField(default=timezone.now)
    student_id = models.ForeignKey(User,on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Upvotes: 1

Views: 24

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

The student_id is a User object, not a string, so here you are comparing a string (the username) with a User object, and a User with username 'testuser', is not the same as a string 'testuser'.

The most elegant solution is probably to compare the user with the user, so:

{% if user == project.student_id %}

So we omit the .username, and compare a User object with a User object.

Note: enumeration (especially in a template, but also in the Django layer itself), is not efficient, you should make a query that does the filtering for you.

You can filter a queryset with:

user_projects = Project.objects.filter(student_id=request.user)

in your view to obtain only projects for which the logged in user is the student.

 

Note: A ForeignKey usually does not have an _id suffix. Django will automatically add an extra field named fieldname_id that stores the primary key to which the foreign key refers. After all, a ForeignKey in Django will lazy load the related object.

Upvotes: 1

Related Questions