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).:

def dashboard(request):
    return render(request,'dashboard.html', )


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


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:

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 class="box">
                   <span class="value">{{ donations }}</span>  
                   <span class="parameter">Donations</span>


Answered By – Alejandro

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published