gpt4 book ai didi

python - 使用一对多关系在 Django 中创建 2 种不同的用户类型

转载 作者:行者123 更新时间:2023-12-01 09:08:07 25 4
gpt4 key购买 nike

我正在创建一个篮球统计应用程序,我希望有两种不同的用户类型:教练和球员。我希望教练能够登录并仅查看他的球员的统计数据。因此,一名教练将拥有多名球员。我希望能够为每个教练创建用户个人资料,并仅显示他们的球员,而不是数据库中的所有球员。到目前为止,我已经创建了显示所有注册用户的用户配置文件,但我对如何分离这两个用户以便球员将在教练的指导下感到困惑。另外,如何在 HTML 中显示教练下列出的所有球员?谢谢!!!

Models.py View :

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save


class UserProfile(models.Model):
name = models.CharField(max_length=100, default='')
school_name = models.CharField(max_length=100, default='')
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default='')
city = models.CharField(max_length=100, default='')
state = models.CharField(max_length=100, default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
jersey_number = models.IntegerField(default=0)
image = models.ImageField(upload_to='profile_image', blank=True)
position = models.CharField(max_length=100, default='')
height = models.CharField(max_length=100, default='')
weight = models.CharField(max_length=100, default='')
grade = models.CharField(max_length=100, default='')
background_image = models.ImageField(upload_to='profile_image', blank=True)

def __str__(self):
return self.user.username


def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

View .py:

@login_required(login_url='login')
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
args = {'user': user}
return render(request, 'accounts/profile.html', args)

所以我以用户身份登录,它显示了两个玩家。我希望它只显示player1,然后以另一位教练的身份登录,它会显示player2。

[![在此处输入图像描述][1]][1]

Django 管理 View :因此,如果我在每个用户下登录,它将显示所有用户。例如:我想在 1 个用户(教练)下登录并显示球员 1-4,然后在另一位教练下登录并显示球员 5-7。[![在此处输入图像描述][2]][2]

HTML View :

<div class="column middle">
<table id="roster" class="table table-bordered table-hover table-condensed"><!--add roster-->
<h2>Roster</h2>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Player Name</th>
<th scope="col">Position</th>
<th scope="col">Grade</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td class="number">{{ user.userprofile.jersey_number }} </td>
<td class="name">
{% if user.userprofile.image %}
<img src="{{ user.userprofile.image.url }}" width="60" height="75" vspace="10">
{% endif %}
<a href="{% url 'view_profile_with_pk' pk=user.pk %}">
{{ user.userprofile.name }}
</a>
</td>
<td class="position">{{ user.userprofile.position }}</td>
<td class="grade">{{ user.userprofile.grade }}</td>
</tr>
{% endfor %}

</tbody>
</table>
</div>

最佳答案

不要对教练和球员使用相同的模型,而是将它们分开。您还可以创建团队的抽象,这是一个好主意,因为您可能希望每个团队能够拥有多名教练,或者让教练在一年指导一支球队,下一年指导另一支球队。

模型.py

class Coach(models.Model):
user = models.OneToOneField("auth.User")
# ... Other info

class Team(models.Model):
coach = models.OneToOneField(Coach)
# ... Other info

class Player(models.Model):
user = models.OneToOneField("auth.User")
team = models.ForeignKey(Team)
# ... Other info

那么如果你想要一名球员教练:

player = Player.objects.get(...)
players_coach = player.team.coach

或者如果您想聘请教练球员:

coach = Coach.objects.get(...)
coaches_players = coach.team.player_set.all()

这还允许您轻松更改教练和球员之间的关系,例如将教练和球队之间的外键更改为ManyToManyField,以便允许每个球队有多名教练以及教练多年来指导多个球队。

------------- 以下是您如何实现它 ----------------

@login_required(login_url='login')
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user

context = {}

if user.coach is not None:
# User is a coach
coach = user.coach
coaches_players = coach.team.player_set.all()
context["coaches_players"] = coaches_players
elif user.player is not None:
# User is a player
player = user.player
players_coach = player.team.coach
context["players_coach"] = players_coach

# Depending on which variables are None and which aren't, the user is a coach or a player.
# If 'player' and 'players_coach' aren't None, then the user is a player and you now have their player object in 'player' and their coach in 'players_coach'.
# If 'coach' and 'coaches_players' aren't None, then the user is a coach and you now have their coach object in 'coach' and their players in 'coaches_players'.

context["user"] = user
return render(request, 'accounts/profile.html', context)

然后在 HTML 模板中:

{% for player in coaches_players %}
<p>{{ player }}</p>
{% endfor %}

关于python - 使用一对多关系在 Django 中创建 2 种不同的用户类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51882213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com