简体   繁体   中英

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. But when I'm calling this method in html template file this shows empty.

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM