Home > Software engineering >  How to filter my data to the active user in Django?
How to filter my data to the active user in Django?

Time:09-19

I'm trying to pull through only the latest data for the active user to my Django template. However, I'm currently receiving the below error.

Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7f0682901a90>.

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:

def health_hub(request):
    model = HealthStats
    
    def get_queryset(self):
        user = self.user
        latest = HealthStats.objects.filter(user=user).latest('date')
        return latest

    context = {
            "user": model.user,
            "weight": model.weight,
            "date": model.date,
            "run_distance": model.run_distance,
            "run_time": model.run_time,
            "stats": HealthStats,
            "latest": get_queryset(model)
        }
    return render(request, 'health_hub.html', context)

health_hub.html:

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


{% block content %}
<div >
    <div >
        <div >
            <h1>My Health Summary</h1>
        </div>
    </div>
</div>
<div >
    <div >
        <h3>Welcome {{ latest.user }}!</h3>
        <p>Please see below for your latest stats:</p>
        <table >
            <tr>
                <td>Weight: {{ latest.weight }}</td>
                <td>Run Distance: {{ latest.run_distance }} km</td>
            </tr>
            <tr>
                <td>Run Time: {{ latest.run_time }}</td>
                <td>Last Updated: {{ latest.date }}</td>
            </tr>
        </table>

According to the error message, it looks like there is an issue with what I'm trying to pull through, but I'm not sure where because I haven't asked for an ID? I'm just trying to filter the data in my models to show the current user's data, sorted by newest first.

CodePudding user response:

It is your real code ? You mix CBV and FBV which is weird... Your variable model contains a class, not an instance. I supposed your context stats is bad too, but i do not find what you want to get with this var ?

Try this code for your view:

def health_hub(request):
    latest = HealthStats.objects.filter(user=request.user).latest('date')

    context = {
            "user": latest.user,
            "weight": latest.weight,
            "date": latest.date,
            "run_distance": latest.run_distance,
            "run_time": latest.run_time,
            "stats": HealthStats,
            "latest": latest
        }
    return render(request, 'health_hub.html', context)

Some help on CBV with Django: https://docs.djangoproject.com/fr/3.2/topics/class-based-views/generic-display/

  • Related