- 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…