[英]Django: Returning models.CharField() value from getter method is empty
Here is my model class. 这是我的模特课。 In this I've added a new getter method
url()
to return a url string for an author profile. 在这里我添加了一个新的getter方法
url()
来返回作者配置文件的url字符串。 But when I'm calling this method in html template file this shows empty. 但是当我在html模板文件中调用此方法时,这显示为空。
See here is my usage example: 看这里是我的用法示例:
Author Model Class: 作者模型类:
from django.db import models
import re
class Author(models.Model):
salutation = models.CharField(max_length=10)
name = models.CharField(max_length=64)
email = models.EmailField()
headshot = models.ImageField(upload_to='author_headshots')
# On Python 3: def __str__(self):
def __unicode__(self):
return self.name
@property
def url(self):
return re.sub(r"[\s|\.|\-|\_|\'|\+]+", "-", self.name)
Passed Author
object context to template from view method: 从视图方法将
Author
对象上下文传递给模板:
from django.shortcuts import render
from author.models import Author
def index(request):
authors = Author.objects.order_by('-name')
return render(request, 'home.html', {
'authors': authors
})
And in template(home.html) using as below: 并在模板(home.html)中使用如下:
{% if authors %}
{% for author in authors %}
<h2><a href="author/{{ author.url }}/">{{ author.name }}</a></h2>
<p>About author {{ author.name }} here</p>
{% endfor %}
{% else %}
No Authors
{% endif %}
Getting output: 获得输出:
<h2><a href="author//">XXX</a></h2>
<p>About author XXX here</p>
...
Expecting: 期待:
<h2><a href="author/xxx/">XXX</a></h2>
<p>About author XXX here</p>
...
I think I have something. 我想我有事。 Instead of defining a property of a model define a global function like this one (in your views file):
而不是定义模型的属性定义像这样的全局函数(在您的视图文件中):
def url(Author):
try:
Author.url=re.sub(r"[\s|\.|\-|\_|\'|\+]+", "-", Author.name)
except:
Author.url='Error!'
and then in your index view add this: 然后在索引视图中添加以下内容:
for author in authors:
url(author)
#print author.url
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.