LaVOZs

The World’s Largest Online Community for Developers

'; How to get user data from template in Django? - LavOzs.Com

It's probably super simple but I found nothing on this specific case. It doesn't help that I messed up a bit and lost track of what does what.

I want my template to display user account balance.

models.py:

from django.contrib.auth.models import User
from django.db import models

class Uzytkownik(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    saldo = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=False)
    telefon = models.CharField(max_length=12, blank=True)
    adres = models.TextField(max_length=255, blank=True)

    def get_balance(self, request):
        current_user = request.user
        return current_user.saldo

view.py:

from django.shortcuts import render

from .models import Uzytkownik, User

def index(request):
    context = {'saldo': Uzytkownik.get_balance}
    return render(request, 'bpanelapp/index.html', context)

In my template, I refer to it using <h2>{{context}}</h2>. Yet the <h2> is empty, even though my currently logged in account's balance field contains data.

First of all, you forgot to call the get_balance function:

def index(request):
    context = {'saldo': Uzytkownik.get_balance(request)}
    return render(request, 'bpanelapp/index.html', context)

Your function itself furthermore will not work: here it requires a self. You need to make this a @staticmethod:

class Uzytkownik(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    saldo = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=False)
    telefon = models.CharField(max_length=12, blank=True)
    adres = models.TextField(max_length=255, blank=True)

    @staticmethod
    def get_balance(request):
        try:
            return request.user.uzytkownik.saldo
        except Uzytkownik.DoesNotExist:
            return None

You can not refer to context. The context variable does not exists, you passed one value to your template (together with some values you pass implicitly like request, and some that are passed through context processors).

You thus render this with:

<h2>{{ saldo }}</h2>

You need to use {{ saldo }} in your template rather than {{ context }} (which doesn't exist). In addition, you need to be passing request into the get_balance method, as it is a required argument.

Related
Extending the User model with custom fields in Django
How to combine two or more querysets in a Django view?
How to get the current URL within a Django template?
Saving form data rewrites the same row
How to check Django version
Can't assign a value (user id) to a ForeignKey field
Customer User Authentication error : AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user_management.CustomUser'
what is the flow of django website… what views, templates, models and forms does actually