Home > Back-end >  how to call a function as a context in django
how to call a function as a context in django

Time:01-30

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 >
    <div >
        {% 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.

CodePudding user response:

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 >
    <div >
        {% for foo in records %}
        <p>{{ foo.get_full_name }}</p>
        {% endfor %}

    </div>
</div>

CodePudding user response:

Everything works fine except your function call,

fullname = User.get_full_name

It should be:

fullname = User.get_full_name()
  • Related