【问题标题】:Type error: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'类型错误:int() 参数必须是字符串、类似字节的对象或数字,而不是“DeferredAttribute”
【发布时间】:2018-09-30 06:14:10
【问题描述】:

我有一张包含艺术家列表的表格和一个查看艺术家详细信息的链接。单击链接时出现此错误:

类型错误:int() 参数必须是字符串、类似字节的对象或数字,而不是 'DeferredAttribute'

谁能解释一下 DeferredAttribute 是什么意思?看起来艺术家 ID 正在被识别(因为当我点击第一个艺术家时它会转到页面 http://127.0.0.1:8000/artist/1),但不是作为整数。

这是我所拥有的:

models.py:

class Artist(models.Model):
    artistID = models.IntegerField(primary_key=True, null=False, unique=True)
    artistName = models.CharField(max_length=50)
    artistNotes = models.TextField(blank=True)

艺术家.html:

{% block content %}
    <table>
        <tr>
            <th>Artist ID</th>
            <th>Artist Name</th>
        </tr>

        {% for artist in artists %}
            <tr>
                <td> {{artist.artistID}} </td>
                <td> {{artist.artistName}} </td>
                <td><a href="{% url 'artist_detail' artistID=artist.artistID %}"
                            title = "Get more information about this artist"> 
                            <img src = "static/images/info.png"></a></td>
            </tr>
        {% endfor %}
    </table>    
{% endblock %}

urls.py:

urlpatterns = [
    path('artist/<int:artistID>', views.artist_detail, name='artist_detail'),
]

views.py:

def artist_detail(request, artistID):
    artist = get_object_or_404(Artist, artistID=Artist.artistID)
    return render(request, 'dtccArt/artist_detail.html', {'artist': artist})

提前感谢您的帮助!

【问题讨论】:

  • Artist.artistID中删除Artist.
  • 太棒了!它有效!

标签: django


【解决方案1】:

在您看来,您使用以下方式获取对象:

    artist = get_object_or_404(Artist, <b>artistID=<s>Artist.artistID</s></b>)

Artist.artistID 是模型字段,而不是您在视图中传递的值。视图有这个参数,因为是和url路径一起传递的,所以需要将值替换为:

def artist_detail(request, artistID):
    artist = get_object_or_404(Artist, artistID)
    return render(request, 'dtccArt/artist_detail.html', {'artist': artist})

然而,上述视图相当常见,最好将其封装在基于类的视图中:DetailView [Django-doc]:

from django.views.generic.detail import DetailView

class ArtistDetailView(DetailView):

    model = Artist
    template_name = 'dtccArt/artist_detail.html'
    context_object_name = 'artist'

    def get_queryset():
        return self.queryset.filter(artistID=self.kwargs.get('artistID'))

urls.py:

urlpatterns = [
    path('artist/', views.ArtistDetailView.as_view(), name='artist_detail'),
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多