Django - Boolean字段在模板中返回false,而在数据库中返回true



你在那里,所以我的问题是完全正如标题所述。在数据库中,boolean字段可以设置为true,但在模板html中,它显示为false。

models.py

class TrainingGoal(models.Model):
forgeid = models.ForeignKey(ForgeUser, on_delete=models.CASCADE, default=None)
strength = models.BooleanField(default=False)
cardio = models.BooleanField(default=False)
yoga = models.BooleanField(default=False)
def __str__(self):
return self.forgeid.forgepass

views.py

def profileView(request):
if not ForgeUser.objects.filter(forgeid=request.user).exists():
return redirect('profileapp:create')
forge_user_query = ForgeUser.objects.get(forgeid=request.user)
training_goal_query = TrainingGoal.objects.filter(forgeid=forge_user_query)

return render(request, 'profileapp/profile.html', {'forge_profile': forge_user_query, 'training_goals': training_goal_query})

删节profile.html

{% if training_goals %}
<div class="goal-container">
<span class={{training_goals.strength | yesno:"training-true,training-false"}}>STRENGTH</span>
<span class={{training_goals.cardio | yesno:"training-true,training-false"}}>CARDIO</span>
<span class={{training_goals.yoga | yesno:"training-true,training-false"}}>YOGA</span>
</div>
{% endif %}

span标签的类值总是显示为training-false,即使将其展开为if语句也会显示返回值为false。我不知道我错过了什么。

问题是在查询集你使用过滤器将返回多个对象。因此,不能使用.<field_name>

访问值
training_goal_query = TrainingGoal.objects.filter(forgeid=forge_user_query)

添加for循环就可以了

{% if training_goals %}
{% for goals in training_goals %}
<div class="goal-container">
<span class={{goals.strength | yesno:"training-true,training-false"}}>STRENGTH</span>
<span class={{goals.cardio | yesno:"training-true,training-false"}}>CARDIO</span>
<span class={{goals.yoga | yesno:"training-true,training-false"}}>YOGA</span>
</div>
{% endfor %}
{% endif %}

最新更新