I am really new in Django and I want to check if Date Stored in Model is passed. In fact, I am currently working on a ticketing app where users would have to purchase and activate ticket and I want to check if the Event Ticket Date is passed upon activation.
My Models:
class Event(models.Model):
event_name = models.CharField(max_length=100)
date = models.DateField(auto_now_add=False, auto_now=False, null=False)
event_venue = models.CharField(max_length=200)
event_logo = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images')
added_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.event_name}"
#Prepare the url path for the Model
def get_absolute_url(self):
return reverse("event_detail", args=[str(self.id)])
class Ticket(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE)
price = models.PositiveIntegerField()
category = models.CharField(max_length=100, choices=PASS, default=None, blank=False, null=False)
added_date = models.DateField(auto_now_add=True)
def __str__(self):
return f"{self.event} "
#Prepare the url path for the Model
def get_absolute_url(self):
return reverse("ticket-detail", args=[str(self.id)])
def generate_pin():
return ''.join(str(randint(0, 9)) for _ in range(6))
class Pin(models.Model):
ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
value = models.CharField(max_length=6, default=generate_pin, blank=True)
added = models.DateTimeField(auto_now_add=True, blank=False)
reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
status = models.CharField(max_length=30, default='Not Activated')
#Save Reference Number
def save(self, *args, **kwargs):
self.reference == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.ticket
class Meta:
unique_together = ["ticket", "value"]
def __str__(self):
return f"{self.ticket}"
def get_absolute_url(self):
return reverse("pin-detail", args=[str(self.id)])
My Views for PIN Activation
def pin_activation(request):
if request.method == "POST":
#Create new form with name form
form = PinActivationForm(request.POST)
#Check if the the form has valid data in it
if form.is_valid():
#Check the status of the user Pin with the one in the Database
check_pin_status = Pin.objects.get(value=form['pin'].value(), status='Not Activated')
#Check if the PIN is correct and NOT ACTIVATED
if check_pin_status:
#Get the Pin, Ticket, Event Date
event_date = check_pin_status.ticket.event.date
current_date = datetime.now()
if event_date > current_date:
messages.error(request, 'Event Has Passed')
return redirect('pages-index')
else:
#Update the User Pin with a new status of Activated
Pin.objects.filter(value=form['pin'].value()).update(status='Validated')
#Message the User
messages.success(request, 'Pin Validated Successfully')
#Redirect the user to register for seat
return redirect('register-guest')
#Check filter the DB where the PIN status is Validated
elif Pin.objects.filter(value=form['pin'].value(), status="Validated"):
messages.error(request, 'Pin Already Validated. Register for Seat')
return redirect('register-guest')
#Check Filter PIN in DB where Status is Activated
elif Pin.objects.filter(value=form['pin'].value(), status="Activated"):
messages.error(request, "Pin Already Activated, Login.")
return redirect('user-login')
else:
messages.error(request, 'Something Went Wrong. Try again')
else:
form = PinActivationForm()
context = {
'form':form,
}
return render(request, 'user/pin_activation.html', context)
Someone should help me on the best way of solving this problem because with my code for checking of date I am having can't compare datetime.datetime to datetime.date.
CodePudding user response:
First you need to get the date from datetime object and then compare it with the event date since your event date is DateField
in your Model
event_date = check_pin_status.ticket.event.date
current_date = datetime.now().date()
if event_date > current_date:
.....
CodePudding user response:
As your error suggest, you can't compare a datetime against a date. Your model field is just a date without any time info. Whereas you are comparing this to timezone.now()
which is a datetime.
This is the offending line:
if event_date > current_date:
Change it to:
if event_date > timezone.now().date():