Home > Net >  Using HTML if statements to return results
Using HTML if statements to return results

Time:03-26

I am trying to print a list of courses that a user has uploaded onto their account but am having trouble figuring out how to do that. I have tried to print {{ course.student_course }} and {{user.username}} and they both appear to print the same thing. But when I do the comparison in the if statement, nothing returns.

Here is the html snippet

<div >
                    <div >
                        {% if courses_list %}
                            {% for course in courses_list %}
                                {% if course.student_course == user.username %}
                                    <button type="button" >{{ subject }} </button>
                                    <p>{{ subject }}</p>
                                {% endif %}
                            {% endfor %} 
                        {% else %} 
                        <p>No courses have been uploaded.</p>
                        {% endif %} 

                    </div>
            </div>

And here is the fields of my model that I am trying to access.

class Course(models.Model):
    subject = models.CharField(max_length=4)
    course_number = models.CharField(max_length=4, default='')
    course_name = models.CharField(max_length=100, default='')
    course_section = models.CharField(max_length=3, default='')
    student_course = models.OneToOneField(User, on_delete=models.CASCADE, default='')

    def __str__(self):
        return self.subject   " "   self.course_number

Like I said, I tried to print each field being compared and they both turned the same thing but when I try to do the comparison it returns nothing.

CodePudding user response:

course.student_course is a User instance

user.username is the username string of the User instance

Therefore you want to use {% if course.student_course == user %} or {% if course.student_course.username == user.username %}

  • Related