[英]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 to call it in my view and show it in my template.我声明了一个 function get_full_name
然后我想在我的视图中调用它并在我的模板中显示它。
views.py:意见.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.但是我无法将模板中的get_full_name
参数作为要显示的值。
You should declare the get_full_name()
as a property not a method so:您应该将get_full_name()
声明为属性而不是方法,因此:
models.py:模型.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:意见.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,一切正常,除了您的 function 电话,
fullname = User.get_full_name
It should be:它应该是:
fullname = User.get_full_name()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.