How to bookmark a page in Django?

前端 未结 1 1394
深忆病人
深忆病人 2020-12-12 08:22

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

Here is the .html file



        
相关标签:
1条回答
  • 2020-12-12 08:53
    • First you modify the models.py that has the user models
    class ProjectUser(AbstractUser):
        images = models.ManyToManyField(Images)
    
        def __str__(self):
            return self.email
    
    • In the .html file add the following:
    {% for image in available_images %}
    /* show image */
    <form method='post' action="{% url 'user-image-add' %}">
     {% csrf_token %}
     <input type='hidden' name='image' value={{image.id}}>
     <button type='submit'>bookmark</button>
    </form>
    {% endfor %}
    
    • In your views.py add the following method
    def user_image_add(request):
        user_image_form = ImageForm(request.POST or None)
        if request.method == 'POST' and user_image_form.is_valid(): 
             request.user.images.add(user_image_form.cleaned_data['image'])
             return JsonResponse(status=200)
        raise Http404()
    
    • Create a forms.py file in your add and add the following:
    class ImageForm(forms.Form):
        image = forms.ModelChoiceField(queryset=Images.objects.all())
    

    To show those bookmarked images you can just iterate over request.user.images (it gives you a QS of Images) similar to code above.


    • In the urls.py add the following:

    path('user-image-add/', views.user_image_add, 'user-image-add')

    • In models.py add a method in User model for getting bool if video is bookmarked
    def is_bookmarked(self, video_id): 
        return self.bookmarked_videos.filter(id=video_id).exists()
    

    simirlarly is_bookmarked can be added to Video model accepting user_id and checking video.projectuser_set.

    And add the following to your .html file where users bookmarked a video

    `{% if video.is_bookmarked %}`
    

    • Delete the UserProfile as you do not need it. Just make sure to have needed instance in context of view.
    0 讨论(0)
提交回复
热议问题