0

I am trying to edit an html page so a logged in user can favorite a video.id

Here is the .html file

<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>

Here is the urls.py file

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'),
]

Here is the view.py file

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)

How to edit the views.py file so it is registered in the database that the user has favorited this video ?

Here is the models.py file

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)
Joseph Adam
  • 1,341
  • 3
  • 21
  • 47

2 Answers2

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)
0

It might not be so obvious, you need to first get the current logged in user by

request.user

if your view function does not require a user to be logged in so you will need to check

if request.user is not None

then add it to the list of favorites to the video

video.favorite.add(request.user)

read more in official docs. many to many

Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45