wyn
wyn

Reputation: 141

Issues getting all users from my django models

I am trying to get all the user from my database to display all the username, goals and goals id using the related name, but I can't seem to do that.

model

class GoalStatus(models.Model):
    status_name = models.CharField(max_length=60)

    def __str__(self):
        return self.status_name



class ScrumyGoals(models.Model):
    goal_status = models.ForeignKey(GoalStatus, on_delete=models.PROTECT, related_name='goalstatus')
    user = models.ForeignKey(User, related_name='scrumygoals', on_delete=models.PROTECT)
    goal_name = models.CharField(max_length=60)
    goal_id = models.IntegerField()
    created_by = models.CharField(max_length=60)
    moved_by = models.CharField(max_length=60)
    owner = models.CharField(max_length=60)

view

def home(request):
    user = User.objects.all()
  #  User1 = ScrumyGoals.objects.filter(goal_name='Learn Django')


    context = {'User': User}
    return render(request, 'django/home.html', context)

template

{% for g in User.scrumygoals_set.all %}
        <td>g.User.User</td>>
        <td>g.goal_name</td>>
        <td>g.goal_id</td>>


    {% endfor %}

the output is supposed to look like this

User      Weekly Goals     Daily Goals     Verify Goals    Done Goals
username    Goalname Goalid Goalname Goalid

Upvotes: 0

Views: 46

Answers (1)

notanumber
notanumber

Reputation: 6529

You can't make a query in the template in that way. Try this:

views.py

def home(request):
    users = User.objects.all()
    context = {'users': users}
    return render(request, 'django/home.html', context)

django/home.html

{% for g in users %}
    <td>{{ g.username }}</td>>
    <td>{{ g.scrumygoals.goal_name }}</td>>
    <td>{{ g.scrumygoals.goal_id }}</td>>
{% endfor %}

Alternatively, if you'd prefer to cycle through ScrumyGoal instances instead, do this:

views.py

def home(request):
    scrumy_goals = ScrumyGoals.objects.all()
    context = {'scrumy_goals': scrumy_goals}
    return render(request, 'django/home.html', context)

django/home.html

{% for g in scrumy_goals %}
    <td>{{ g.user.username }}</td>>
    <td>{{ g.goal_name }}</td>>
    <td>{{ g.goal_id }}</td>>
{% endfor %}

Upvotes: 1

Related Questions