Commit 987546e3 authored by Ilham Maulana's avatar Ilham Maulana 💻

fix: custom validators for loans

parent 8efffb91
from django.db import models from django.db import models
from django.utils import timezone
from book.models import Book from book.models import Book
from users.models import Member from users.models import Member
from .validators import validate_due_date, validate_loan_date
class BookLoan(models.Model): class BookLoan(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE)
member = models.ForeignKey(Member, on_delete=models.CASCADE) member = models.ForeignKey(Member, on_delete=models.CASCADE)
loan_date = models.DateTimeField() loan_date = models.DateTimeField(validators=[validate_loan_date])
due_date = models.DateTimeField() due_date = models.DateTimeField(validators=[validate_due_date])
return_date = models.DateTimeField(blank=True, null=True) return_date = models.DateTimeField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now=True)
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
def validate_loan_date(value):
now = timezone.now()
loan_date = value
if loan_date > now:
raise ValidationError(
_("Loan date cannot be later than today"),
params={"value": value},
)
def validate_due_date(value):
due_date = value
loan_date = timezone.now()
if due_date < loan_date:
raise ValidationError(
_("Due date cannot be less than loan date"),
params={"value": value},
)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment