Django views.py:添加到收藏夹页面

时间:2019-03-28 12:47:40

标签: python django

我正在尝试编辑html页面,以便登录用户可以收藏video.id

这是 .html 文件

<td>
    <form method='POST' action="{% url 'foobar:favourite_post' video.id %}">
        {% csrf_token %}
        <input type='hidden' name='video' value={{ video.id }}>
        <button type='submit'>Bookmark</button>
    </form>
</td>

这是 urls.py 文件

app_name = 'foobar'

urlpatterns = [
    path('', views.f_ListView.as_view(), name='overview'),
    path('<int:pk>/', views.f_DetailView.as_view(), name='detailview'),
    path('<int:fav_id>/favourite_post/', views.favourite_post, name='favourite_post'),
]

这是 view.py 文件

def favourite_post(request, fav_id):
    video = get_object_or_404(Video, id=fav_id)
    if request.method == 'POST': #Then add this video to users' favourite
        video.

   return render(request, 'foobar/%s' % fav_id)

如何编辑 views.py 文件,以便将其注册到用户喜欢该视频的数据库中?

这是 models.py 文件

from django.contrib.auth.models import AbstractUser

class ProjectUser(AbstractUser):

    def __str__(self):
        return self.email

class Video(models.Model):
    name = models.CharField(max_length=255),
    videofile = models.FileField(upload_to="static/videos/"),
    favourite = models.ManyToManyField(ProjectUser, related_name="fav_videos", blank=True)

2 个答案:

答案 0 :(得分:1)

def favourite_post(request, fav_id):
video = get_object_or_404(Video, id=fav_id)
    if request.method == 'POST':
        video.favourite.add(request.user)
        # Rest code
    return render(request, 'foobar/%s' % fav_id)

答案 1 :(得分:0)

可能不太明显,您需要先通过

获取当前登录的用户
request.user

如果您的查看功能不需要用户登录,则需要检查

if request.user is not None

然后将其添加到视频的收藏夹列表中

video.favorite.add(request.user)

在官方文档中了解更多信息。 many to many