How to call a function as a context in django

class User(AbstractUser):
    GENDER_STATUS = (
        ('M', 'Male'),
        ('F', 'Female')
    )
    address = models.TextField(null=True, blank=True)
    age = models.PositiveIntegerField(null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    gender = models.CharField(max_length=1, choices=GENDER_STATUS, null=True, blank=True)
    phone = models.CharField(max_length=15, null=True, blank=True)

    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

i declare a function get_full_name and then i want too call it in my view and show it in my template. this is my view

from django.shortcuts import render
from accounts.models import User


def about_us(request):
    fullname = User.get_full_name
    context = {
        'fullname': fullname
    }
    return render(request, 'about_us.html', context=context)

and this is my template as you can see i used a loop for my context

<div class="container">
    <div class="d-flex flex-wrap justify-content-around">
        {% for foo in fullname %}
        <p>{{ foo }}</p>
        {% endfor %}

    </div>
</div>

but i cant get the get_full_name parameters in my template as value too show. i'll be more than happy if sombodey help me. THANK YOU!

You should declare the get_full_name() as a property not a method so:

models.py:

class User(AbstractUser):
    GENDER_STATUS = (
        ('M', 'Male'),
        ('F', 'Female')
    )
    address = models.TextField(null=True, blank=True)
    age = models.PositiveIntegerField(null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    gender = models.CharField(max_length=1, choices=GENDER_STATUS, null=True, blank=True)
    phone = models.CharField(max_length=15, null=True, blank=True)

    @property
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

views.py:

from django.shortcuts import render
from accounts.models import User


def about_us(request):
    objs = User.objects.all()
    context = {
        'records': objs
    }
    return render(request, 'about_us.html',context)

Template file:

<div class="container">
    <div class="d-flex flex-wrap justify-content-around">
        {% for foo in records %}
        <p>{{ foo.get_full_name }}</p>
        {% endfor %}

    </div>
</div>

Everything works fine except your function call,

fullname = User.get_full_name

It should be:

fullname = User.get_full_name()
Back to Top