How to bookmark a page in Django?

耗尽温柔 提交于 2019-11-28 14:51:16
  • 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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!