人。
我想检查我的django模板,如果 request.user 存在于我的表 LeagueMember 中的某行列用户中。我发现的方式不起作用。
views.py
@login_required(login_url='login/')
def search_leagues(request):
if request.method == 'POST':
return redirect('join_league')
leagues = League.objects.all()
return render(request, 'search_leagues.html', { 'allleagues': leagues })
model.py
class League(models.Model):
league_owner = models.ForeignKey('auth.User')
league_name = models.CharField(max_length=30)
creation_date = models.DateTimeField()
def is_member(self):
member = LeagueMember.objects.get(league=self)
if member:
return True
else:
return False
class LeagueMember(models.Model):
league = models.ForeignKey('League', related_name='leaguemember_league')
user = models.ForeignKey('auth.User')
search_leagues.html
{% for league in allleagues %}
<tr>
<td class="center">{{ league.league_name }}</td>
<td class="center">{{ league.leaguemember_league.count}}/{{ league.leaguesettings_league.league_number_teams }}</td>
<td class="center">{{ league.leaguesettings_league.league_eligibility }}</td>
<td class="center">{{ league.leaguesettings_league.league_lifetime }}</td>
{% if request.user in league.leaguemember_league.user %}
DO SOMETHING!!!
{% else %}
{% if league.leaguemember_league.count < league.leaguesettings_league.league_number_teams %}
{% if league.leaguesettings_league.league_eligibility == "Private" %}
<form method="post" action="{% url 'joinleague' pk=league.id %}">
<td class="center"><a href="{% url 'joinleague' pk=league.id %}" class="btn btn-mini btn-warning">Soliticar</a></td>
</form>
{% elif league.leaguesettings_league.league_eligibility == "Public" %}
<form method="post" action="{% url 'joinleague' pk=league.id %}">
<td class="center"><a href="{% url 'joinleague' pk=league.id %}" class="btn btn-mini btn-info">Entrar</a></td>
</form>
{% endif %}
{% endif %}
{% endif %}
</tr>
{% endfor %}
此错误在此行中:
{% if request.user in league.leaguemember_league.user %}
始终进入ELSE区块
谢谢大家
答案 0 :(得分:0)
DataFrame
不会为您提供league.leaguemember_league
个对象,而是RelatedManager
个对象(因此您无法在其中找到LeagueMember
属性,因此您的模板逻辑将无效) 。
您要做的是在您的关系中深入两个级别(user
- &gt; League
- &gt; LeagueMember
)。您无法轻松地在模板中执行此类逻辑,而可能需要在视图代码中执行此操作。例如:
User
然后,您需要修改所有模板逻辑以使用此新结构:
league_data = []
for league in League.objects.all():
league_data.append({
'league': league,
'users': User.objects.filter(leaguemember__league=league) # This gives you all the users that are related to this league
})
return render(request, 'search_leagues.html', { 'allleagues': league_data})
然后在{% for league_data in allleagues %}
# Replace league with league_data.league in all the template logic below this
区块中,您可以执行以下操作:
if
请注意,如果您拥有大量用户/联盟,此查询可能效率不高 - 在这种情况下,您可能需要重新考虑您的模型设计。