Joseph Adam
Joseph Adam

Reputation: 1642

How to access Django Model field value?

The following html code fails to switch between "Bookmark" and "Unbookmarked" if there is more than 1 video being bookmarked with the same user.

How can I changed the following if loop to check if this specific user has bookmarked this specific video rather than a user having a bookmarked video in general ?

<td>
    <form method='POST' action="{% url 'view:favourite' details.id %}">
        {% csrf_token %}
        <input type='hidden'>
        {% if user.fav_videos.exists %}
            <button type='submit'>UnBookmark</button>
        {% else %}
            <button type='submit'>Bookmark</button>
        {% endif %}
    </form>
</td>

The models.py

class Post(models.Model):
    favourite = models.ManyToManyField(User, related_name="fav_videos", blank=True)

The urls.py

path('favourite_post/<int:fav_id>', views.favourite_post, name='favourite_post')

The views.py

def favourite_post(request, fav_id):
    post = get_object_or_404(Post, id=fav_id)
    if request.method == 'POST':
        if post.favourite.filter(id=request.user.id).exists():
            post.favourite.remove(request.user)

        else:
            post.favourite.add(request.user)

        # Rest code
    return HttpResponseRedirect(reverse('detailview', args=(fav_id,)))

The detailed class in the views.py

class DetailView(LoginRequiredMixin, DetailView):
    context_object_name = "details"
    model = Post
    template_name = "detail.html"

Comment on answers: Both @Daniel and @andreihondrari works fine, one is more efficient than the other.

Upvotes: 0

Views: 207

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599470

You could write a template tag to query each video and find if the user is included in the users who favourited it, but that's not very efficient. It's probably much easier to get a list of the user's favourites in one go and pass it to the template:

favourite_ids = request.user.fav_videos.values_list('id', flat=True)

and in the template:

{% if detail.id in favourite_ids %}

Upvotes: 2

andreihondrari
andreihondrari

Reputation: 5833

You could create a template filter like:

@register.filter
def is_bookmarked(video, user):
    return user.fav_videos.filter(id=video.id).exists()

And then use it in your template like:

{% if detail|is_bookmarked:user %}

Upvotes: 2

Related Questions