0

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!

2
  • 2
    Try to change your forloop to this {% for i in user.task_set.all %} Commented Oct 21, 2016 at 17:29
  • i_set? what is i set? Commented Oct 21, 2016 at 17:32

1 Answer 1

1

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 %}
Sign up to request clarification or add additional context in comments.

4 Comments

That worked! thank you so much, I've been really struggling here. I'm still a bit confused as to where the "task" comes from, because I have no "task" in my code, only "Task". Does this disregard capital letters?
@aajw98 You need to understand Related Object Reference
Why is it "much better" to use related_name? What's wrong with the default?
@DanielRoseman As i have wrote for ease of access there is nothing wrong in using default way. It's just my preference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.