Search code examples
pythondjangodjango-modelsdatefield

Django model DateField attribute limit choices


background: So im trying to build a "Bill" model with the attributes Name (name of payee), Amount (how much $ to pay), and PayDate (when to pay the bill).

What I am stuck on: I'm having some hard time trying to limit the PayDate input from 1 (first of the month) to 31 (last day of the month (Depending on the month))

This is my code for the model:

from django.db import models

# Create your models here.


class Bill(models.Model) :
    Name = models.CharField(max_length=200, editable=True, blank=False)
    Amount = models.DecimalField(editable=True, blank=False, decimal_places=2, max_digits=6)
    PayDate = models.IntegerField(
        blank=False, editable=True)

def __str__(self):
    return f"{self.Name} @ ${self.Amount} every {self.PayDate} of the month"

I would love to get your suggestions on how to set the PayDate attribute.


Solution

  • IntegerFields have a MinValueValidator and a MaxValueValidator. Validatiors can be used like so:

    PayDate = models.IntegerField(
            blank=False, editable=True, validators=[MinValueValidator(1),MaxValueValidator(31)])
    

    If you want the maximum value to change depending on the month you will have to do that in your form as validations on the models are fixed