0

I am trying to check if an object instance already exists in the model or if it's empty. I'm new to Django and I can't figure out the logic behind making that happen here. This is my function code and what I'm trying to do (In views.py):

def registerAttendee(request,pk):
    act = Activity.objects.get(pk=pk)
    act.save()
    attendee, _ = Attendee.objects.get_or_create(student=request.user)
    if act.attendee.get(student=request.user) is None:
        act.attendee.add(attendee)
        messages.success(request, 'You\'re successfully registered as an attendee!', extra_tags='alert')
    else:
        messages.warning(request, 'You\'re already registered as an attendee!', extra_tags='alert')
        return redirect('home/#work')

I'm basically checking, if the user is not registered in this activity, then I'm going to add him/her, but if the user is already registered, I'm displaying a specific message. My current code doesn't work because I'm getting an "Invalid Syntax" error on the word None. I tried replacing it with NULL and BLANK but I'm still getting this error. What do I replace it with?

This is what I have in models.py in case it helps:

class Attendee(models.Model):
student = models.ForeignKey(User, related_name="attendee")

class Activity(models.Model):
type = models.CharField(max_length=50, default="")
title = models.CharField(max_length=200, default="")
description = models.CharField(max_length=500)
owner = models.ForeignKey(User, related_name="owner")
college = models.CharField(max_length=200)
location = models.CharField(max_length=200)
room = models.CharField(max_length=200)
startDate = models.DateTimeField(null=True, blank=True)
endDate = models.DateTimeField(null=True, blank=True)
attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True)
volunteer = models.ManyToManyField(Volunteer, related_name="volunteers",null=True, blank=True)
w.y
  • 99
  • 2
  • 11
  • @David I fixed these in my question, the problem is I'm getting a DoesNotExist error at the if statement – w.y Dec 08 '17 at 19:39
  • 2
    `get` throws a `DoesNotExist` exception if asked for something that doesn't exist, the docs should explain that (https://docs.djangoproject.com/ko/1.11/topics/db/queries/#retrieving-a-single-object-with-get ). If you just want to test for presence/absence, use `if act.attendee.filter(student=request.user).exists():` – Peter DeGlopper Dec 08 '17 at 19:40
  • @David you could also add the link to retrieving objects in Django. There is a section on the difference between .get() and filter() https://docs.djangoproject.com/en/1.11/topics/db/queries/#retrieving-objects – Ouss Dec 08 '17 at 19:58

0 Answers0