我想显示当其他用户访问他的public_profile页面时,从Book
模型发布的用户,为此,我必须使用此方法:
def public_profile(request, slug):
profile = get_object_or_404(Profile, slug=slug)
book = Book.objects.get(slug=slug)
context = {
'profile': profile,
'book': book
}
return render(request, 'public_profile.html', context)
但使用该方法返回:public_profile
模板中的Book matching query does not exist.
。public_profile
页面:
<p class="title is-4"><a href="{{ book.get_user_public_url }}">
{{ book.user }}
</a></p>
我的模型
class Book(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
audio = models.FileField(upload_to='audio')
title = models.CharField(max_length=50)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image = models.ImageField(upload_to='audio-image')
introduction = models.TextField(max_length=500)
slug = models.SlugField(unique=True)
def get_user_public_url(self):
return reverse('Public-Profile', kwargs={'slug': self.user.profile.slug})
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
profile_photo = models.ImageField(upload_to='profile-image', default='static/dafault.jpg')
twitter = models.URLField(blank=True, null=True, unique=True)
website = models.URLField(blank=True, null=True, unique=True)
linkedln = models.URLField(blank=True, null=True, unique=True)
country = models.CharField(max_length=70, blank=True, null=True,)
about = models.TextField(max_length=700, blank=True, null=True)
slug = models.SlugField(max_length=100, unique=True)
1条答案
按热度按时间7vux5j2d1#
问题是我试图使用
slug=slug
获取Book
对象,这与检索Profile
对象所使用的参数相同。然而,slug
是Book对象的唯一字段,因此我实际上试图使用错误的字段检索Book对象。为了解决这个问题,我尝试使用下面的方法:
但我得到了这个错误:
get return more than one Book --it returned 2!
因为@WillemVanOnsem在评论区说:what is book supposed to be? It is not said that the profile has any book, and it is also possible that it has multiple books.
表示:在我的数据库中有两个或多个Book对象,它们与我试图检索的Profile对象关联的User对象具有相同的user值。所以我把代码改成这样:
并使用以下命令为该用户获取
Book
: