aajw98 aajw98 - 3 years ago 77
Python Question

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:

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

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

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!

Answer Source

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 %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download