Django 模板用户请求
我有一本模型书,可以添加到用户的收藏夹中。 所以我定义了 2 个类:
class Book(models.Model):
name = models.CharField(max_length = 40)
class UserFavorite(models.Model):
book = models.ForeignKey(Book)
user = models.ForeignKey(User)
现在我想在主页上显示热门书籍,并带有“添加到收藏夹”或“从收藏夹中删除”图标。 基本上,我将流行书籍数组传递给模板,然后从模板中循环遍历该数组,并应该说“if book.is_in_favorites(request.user): ...”,但这在模板中是不可能的。
I have a model Book which can be added to user's Favorites. So I defined 2 classes:
class Book(models.Model):
name = models.CharField(max_length = 40)
class UserFavorite(models.Model):
book = models.ForeignKey(Book)
user = models.ForeignKey(User)
Now I'd like to show on the main page popular books with an icon either "add to favorites" or "remove from favorites". Basically I pass array of popular books to a template and from the template I loop thru this array and should say "if book.is_in_favorites(request.user): ...", but this is not possible from template.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最常见的方法是在视图中装饰书籍对象。 在视图代码中,循环遍历书籍,添加一个布尔值来指示它们是否是当前用户的最爱:
然后在模板中:
如果您不喜欢修改书籍对象,则可以创建一个字典列表用注释包裹书籍:
并在模板中使用它:
The most common approach to this would be to decorate the book objects in the view. In the view code, loop over the books, adding a boolean indicating whether they are a favorite of the current user or not:
then in the template:
If you don't like modifying the book objects, you can make a list of dicts that wraps up books with their annotations:
and use it in your template:
我不明白这和模板有什么关系。 您只需要显示一个指向视图的链接,该视图将图书 ID 作为参数,从请求中获取用户,并使用这两者添加 UserFavourite。
编辑后更新:好的,我现在明白您的问题了。 嗯,正如您所发现的,这种事情太复杂,无法放入模板逻辑中。 它确实需要放在您的视图中或模板标记中。 模板标签可能是最好的,因为您无疑会希望在多个视图/模板中使用此功能。
您可能想要使用包含标签,因为它的好处是能够自动获取上下文。 类似于(未经测试):
现在您只需要一个模板片段,它使用上面标签返回的书籍中的值来呈现列表。 在主模板中,只需使用
favourite_links
即可显示图书链接。I don't understand what this has to do with templates. You just need to display a link to a view that takes the book id as a parameter, gets the user from the request, and adds a UserFavourite using the two.
Update after edit: OK, I understand your issue now. Well, as you've found, this sort of thing is too complex to put into template logic. It really needs to go either in your view, or in a template tag. Probably a template tag is best, as you will no doubt want to use this functionality in multiple views/templates.
You will probably want to use an inclusion tag, as that has the benefit of being able to take the context automatically. Something like (untested):
Now you just need a template fragment which renders a list using the values in books returned by the tag above. And in your main template, just use
favourite_links
to show the book links.