【问题标题】:'str' object has no attribute '_meta' error when trying to get access to a Model field verbose_name dynamically from template尝试从模板动态访问模型字段 verbose_name 时,“str”对象没有属性“_meta”错误
【发布时间】:2014-11-13 15:57:47
【问题描述】:

Django 1.7

我有一个模型:

class Book(models.Model):
    author = models.CharField(
        'Автор',
        max_length = 200, 
        blank = True
    )
    title = models.CharField(
        'Заглавие',
        max_length = 200
    )
    pub_year = models.IntegerField(
        'Год издания', 
        max_length = 4, 
        choices = YEAR_CHOICES
    )

在我的views.py 我有:

from django.shortcuts import render, redirect, get_object_or_404
from django.views import generic
from books.models import Book
from forms import BookForm

class BookListView(generic.ListView):

    model = Book
    paginate_by = 25

我想在模板中获取 verbose_names 的 Book 模型字段。为了做到这一点,我注册了模板标签(功能代码来自https://stackoverflow.com/a/2429094/2947812):

@register.filter
def verbose_name(value, arg): 
    return value._meta.get_field_by_name(arg)[0].verbose_name 

在模板中我是这样使用的:

{{ book|verbose_name:"title" }}

据我所知,一切都是按照Django documentation on custom template tags and filters制作的。

但我得到的是'str' object has no attribute '_meta' error,而不是verbose_name 值。我猜这是因为不是 Book 对象,而是传递给 verbose_name 函数的其他东西,但为什么呢?

【问题讨论】:

  • 请出示您的查看代码
  • @user2717954 帖子中有views.py代码。
  • 抱歉,直到此刻我才知道 ListView,但从阅读文档看来,您需要执行 {% for book in object_list %} {{ book|verbose_name:"title" }} {% %} 结束。这是您尝试访问变量 book 的方式吗?
  • 好吧,我将book 更改为book_list.0,现在可以了。但是如果 book_list 中没有项目,那么我会得到另一个错误...
  • 这个问题还没有解决吗?我有一个类似的问题,但你的具体情况似乎不一致。你能回答你自己的问题或以更有意义的方式重新格式化吗?

标签: python django


【解决方案1】:

我错误地使用了{{ book|verbose_name:"title" }},而没有设置变量book。我的模板是用于 ListView 的,book 仅在{% for book in book_list %} ... {% endfor %} 循环内设置。所以我用这种方式重写了我的模板:

<table class="table table-striped">
    <thead>
        <tr>
            <th>ID</th>
            <th>{{ book_list.0|verbose_name:"author" }}</th>
            <th>{{ book_list.0|verbose_name:"title" }}</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        {% for book in book_list %}
            <tr>
                <td>{{ book.id }}</td>
                <td>{{ book.author }}</td>
                <td>{{ book.title }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多