[英]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}'
我聲明了一個 function get_full_name
然后我想在我的視圖中調用它並在我的模板中顯示它。
意見.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)
這是我的模板,你可以看到我為我的上下文使用了一個循環
<div class="container">
<div class="d-flex flex-wrap justify-content-around">
{% for foo in fullname %}
<p>{{ foo }}</p>
{% endfor %}
</div>
</div>
但是我無法將模板中的get_full_name
參數作為要顯示的值。
您應該將get_full_name()
聲明為屬性而不是方法,因此:
模型.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}'
意見.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)
模板文件:
<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>
一切正常,除了您的 function 電話,
fullname = User.get_full_name
它應該是:
fullname = User.get_full_name()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.