Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – Boolean field returns false in template while true in database

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 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 %}

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.

>Solution :

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 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 %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading