Reputation: 29
I am trying to make a query where the current logged in user can view the Teams they have created. Therefore I am trying to print a list of the UserTeams where the UserID = the current user's ID. I know I need to use the 'owner' field i have created for the Teams, though I don't really know where/ what to do.
Here is my view:
def teamsview(request):
query = UserTeams.objects.filter(userID=request.user)
return render(request, 'teammanager/teams.html', {
"teams": query})
My Teams and UserTeams models:
class Team(models.Model):
name = models.CharField(max_length=100)
venue = models.CharField(max_length=100)
countryID = models.ForeignKey(Countries, on_delete=models.CASCADE)
owner = models.ForeignKey(User)
def __str__(self):
return self.name
class UserTeams(models.Model):
userID = models.ForeignKey(User,on_delete=models.CASCADE)
teamID = models.ForeignKey(Team,on_delete=models.CASCADE)
And my HTML:
{%for team in userteams%}
<h3><a href='/teams/{{userteam.id}}'>{{team.name}}</a></h3>
{%endfor%}
Upvotes: 0
Views: 240
Reputation: 308829
Are you sure you need the UserTeams
model? Your Team
model already has a foreign key to the User
model:
class Team(models.Model):
...
owner = models.ForeignKey(User)
Therefore, in your view you can do:
from django.contrib.auth.decorators import login_required
@login_required
def teamsview(request):
query = Teams.objects.filter(owner=request.user)
return render(request, 'teammanager/teams.html', {
"teams": query})
The login_required
decorator makes sure that only logged-in users can access the view.
Then in your template, loop through teams
, to match the {"teams": query}
context from your view.
{% for team in teams %}
<h3><a href='/teams/{{ team.id }}'>{{team.name}}</a></h3>
{% endfor %}
Upvotes: 1