我想为我的播放列表模型创建详细信息视图。我遵循了docs的步骤,并且不断收到此错误:
AttributeError at /root
Generic detail view PlaylistDetail must be called with either an object pk or a slug in the URLconf.
这是我的代码:
型号:
class Playlist(models.Model):
title = models.CharField(max_length=40, null=True)
description = models.CharField(max_length=500, null=True)
author = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
miniature = models.ImageField(upload_to='images/playlist', default="defaults/default.png", validators=[validate_miniature_file_extension])
tracks = models.ManyToManyField(Track)
def __str__(self):
return self.title
url:
path('<slug:author>', PlaylistDetail.as_view(), name='playlist'),
视图:
class PlaylistDetail(DetailView):
model = Playlist
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context
我想它的原因是同一用户创建了多个播放列表,并且它必须获得用户&&标题。有什么建议吗?
答案 0 :(得分:1)
问题在于,您在网址中使用<slug:author>
path('<slug:author>', PlaylistDetail.as_view(), name='playlist'),
默认情况下,它会寻找slug
。
尝试使用以下方法更新视图:
class PlaylistDetail(DetailView):
model = Playlist
slug_url_kwarg = 'author' # <----
def get_context_data(self, **kwargs):
# . . .