我有一张桌子,上面有艺术家的名单,以及一个链接,以查看艺术家的详细信息。单击链接时出现此错误:
类型错误:int()参数必须是字符串,类似字节的对象或数字,而不是'DeferredAttribute'
有人可以解释DeferredAttribute的含义吗?好像可以识别artistID(因为当我单击第一个歌手时,它会转到页面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)
artists.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})
在此先感谢您的帮助!
答案 0 :(得分:1)
在您看来,您可以通过以下方式获取对象:
artist = get_object_or_404(Artist, artistID=Artist.artistID)
但是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'),
]