[Answered ]-Checking whether element is in ManyToMany field in Django

1👍

You can check with:

from django.shortcuts import get_object_or_404, redirect

def attend_session(request):
    session = get_object_or_404(Study, pk=request.POST['session_id'])
    stud = get_object_or_404(Student, student_user=request.user)

    if request.method == 'POST':
        if stud not in session.attendees.all():
            session.attendees.add(stud)

    return redirect('study:sessions')

Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.


Note: You can make use of redirect(…) [Django-doc] instead
of first calling reverse(…) [Django] and
then wrap it in a HttpResponseRedirect object [Django-doc].
The redirect(…) function does not only offer a more convenient signature to do this, it also for example will use the
.get_absolute_url() method [Django-doc]
if you pass it a model object.

Leave a comment