how to call a function as a context in django

Question:

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 to call it in my view and show it in my template.

views.py:

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 can’t get the get_full_name parameters in my template as value to show.

Asked By: HesamHashemi

||

Answers:

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>
Answered By: Sunderam Dubey

Everything works fine except your function call,

fullname = User.get_full_name

It should be:

fullname = User.get_full_name()
Answered By: Nimra Tahir