Home > Net >  Django - Boolean field returns false in template while true in database
Django - Boolean field returns false in template while true in database

Time:07-08

Yo ho there, so the issue i'm having is exactly as the title states. In the database, the boolean field can be set as true, but in the template html, it shows up as 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})

abridged profile.html

    {% if training_goals %}
      <div >
        <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 %}

The class value of span tag always shows up as training-false, and even expanding it into an if statement shows that the returned value is false. Not sure what I'm missing here.

CodePudding user response:

Problem is in the query set you're using filter which will return more than one objects. So, you cann't access values using .<field_name>

training_goal_query = TrainingGoal.objects.filter(forgeid=forge_user_query)

Add for loop and it will work fine

{% if training_goals %}
{% for goals in training_goals %}
<div >
  <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 %}
  • Related