Home > Software engineering >  How do I bring through my data in Django Template view?
How do I bring through my data in Django Template view?

Time:09-19

I'm trying to display my data from my HealthStats model to my template, however I can only pull through the user field. I've added the other fields to my template, but they're not showing. I would also like to be able to filter the output to only show records of the logged in user.

Models.py

class HealthStats(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateField(auto_now=True)
    weight = models.DecimalField(max_digits=5, decimal_places=2)
    run_distance = models.IntegerField(default=5)
    run_time = models.TimeField()

    class Meta:
        db_table = 'health_stats'
        ordering = ['-date']

    def __str__(self):
        return f"{self.user} | {self.date}"

Views.py:

class HealthHistory(generic.TemplateView):
    model = HealthStats
    template_name = 'health_hub_history.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['stats'] = HealthStats.objects.all()
        return context

health_hub_history.html

{% extends 'base.html' %}
{% load static %}

{% block content %}
<div >
    <div >
        <div >
            <h1>My Health History</h1>
        </div>
    </div>
</div>
<div >
    <div >
        <div >
            <table >
                <tr>
                    <td>User:</td>
                    <td>Weight (lbs):</td>
                    <td>Date:</td>
                    <td>Run Distance (km):</td>
                    <td>Run Time (HH:MM:SS):</td>
                </tr>
                {% for stat in stats %}
                <tr>
                    <td>{{ user }}</td>
                    <td>{{ weight }} </td>
                    <td>{{ date }}</td>
                    <td>{{ run_distance }}</td>
                    <td>{{ run_time }}</td>
                </tr>
                {% endfor %}
            </table>
        </div>
    </div>
</div>
{% endblock content %}

Any help would be appreciated!

CodePudding user response:

In your template do this:

                {% for stat in stats %}
                <tr>
                    <td>{{stat.user}}</td>
                    <td>{{stat.weight}} </td>
                    <td>{{stat.date}}</td>
                    <td>{{stat.run_distance}}</td>
                    <td>{{stat.run_time}}</td>
                </tr>
                {% endfor %}

hope it will work

  • Related