Django:从getter方法返回models.CharField()值为空

时间:2013-11-05 12:15:16

标签: python django django-models django-templates

这是我的模特课。在这里我添加了一个新的getter方法url()来返回作者个人资料的url字符串。但是当我在html模板文件中调用此方法时,这显示为空。

请参阅此处是我的用法示例:

作者模型类:

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)

通过查看方法将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
                                         })

在模板(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 %}

获取输出:

<h2><a href="author//">XXX</a></h2>
<p>About author XXX here</p>
...

期待:

<h2><a href="author/xxx/">XXX</a></h2>
<p>About author XXX here</p>
...

1 个答案:

答案 0 :(得分:0)

我想我有事。而不是定义模型的属性定义像这样的全局函数(在您的视图文件中):

def url(Author):
    try:
        Author.url=re.sub(r"[\s|\.|\-|\_|\'|\+]+", "-", Author.name)
    except:
        Author.url='Error!'

然后在索引视图中添加:

for author in authors:
    url(author)
    #print author.url
相关问题