Search code examples
pythondjangomodel

Getting model data associated with a username and displaying it in HTML in Django


I have a model that associates points and donations with a user. In my view, I want to get the data for the user who is currently logged in and display his donations and points in HTML. How would I go about doing this? The model, view, and HTML are down below.

View (I want to get the points and donations assosicated with the user currently logged in).:

@login_required(login_url='/login/')
def dashboard(request):
    return render(request,'dashboard.html', )

Model:

  class userdetails(models.Model):
      donations = models.IntegerField(blank=True, null = True,)
      points = models.IntegerField(blank=True, null = True,)
      user = models.ForeignKey(
            settings.AUTH_USER_MODEL,
            on_delete=models.CASCADE,
            blank=True,
            null=True,
        )

Solution

  • Per the [docs on render][1] you can pass in context, a dictionary of values to add to the template context. So in your view you will need to something along the lines of:

    @login_required(login_url='/login/')
    def dashboard(request):
        user = request.user
        # assuming there is exactly one
        # this will break if there are multiple or if there are zero
        # You can (And should) add your own checks on how many userdetails objects you have for the user
        # consider using a OneToOneField instead of a ForeignKey
        user_details = user.userdetails_set.get()  # or userdetails.objects.get(user=user)
        context = {
            "donations": user_details.donations,
            "points": user_details.points,
        }
        return render(request,'dashboard.html', context=context)
    

    Then in your HTML you can use [Django's template language][2]:

    <div class="box">
                       <span class="value">{{ points }}</span>  
                       <span class="parameter">Points</span>
                    </div>
    
    
    <div class="box">
                       <span class="value">{{ donations }}</span>  
                       <span class="parameter">Donations</span>
                    </div>
    
    
      [1]: https://docs.djangoproject.com/en/3.2/topics/http/shortcuts/#render
      [2]: https://docs.djangoproject.com/en/3.2/ref/templates/language/#variables