aajw98
aajw98

Reputation: 51

Django HTML 'for loop' not displaying any of the objects in a set

so I am having trouble with my for loop which is meant to display all the tasks allocated to a user. There are four tasks allocated to them, as you can see on this imgur link . However it does not show them on the site.

Here is my detail.html file:

<h1>{{user.fullName}}</h1>
<h4>Username: {{user.userName}}</h4>

<ul>
    {% for i in userName.i_set.all %}
        <li> {{ i.taskName }} </li>
    {% endfor %}
</ul>

Here is my models.py:

from django.db import models

class User(models.Model):
    userName = models.CharField(max_length=30)
    password = models.CharField(max_length=100)
    fullName = models.CharField(max_length=50)

    def _str_(self):
        return self.fullName

class Task(models.Model):
    userName = models.ForeignKey(User, on_delete=models.CASCADE)
    taskName = models.CharField(max_length=30)
    scores = models.CharField(max_length=100)  # score should default be set to x/10 until changed

    def _str_(self):
        return str(self.userName) + ' - ' + self.taskName

I know its a pain to help someone you don't know but I'd really appreciate it as ive been working on this problem for an hour and managed nothing and I'm really eager to learn what the problem is... thanks so much and have a nice day!

Upvotes: 0

Views: 323

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39649

Based on the code you have provided your for loop code is completely wrong, try to change it to:

{% for i in user.task_set.all %}

More better is to use related_name in ForeignKey for ease of access:

userName = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tasks')

Then you can access related tasks for user in template like this:

{% for i in user.tasks.all %}

Upvotes: 1

Related Questions