Yousuf Jawwad
Yousuf Jawwad

Reputation: 3097

Setting default year as current year in realtime without using DateField

this is how i am doing it right now.

class Season(models.Model):
    Name = models.CharField(max_length=20)
    Year = models.CharField(max_length=6)
    start_date = models.DateField()
    end_date = models.DateField()
    league = models.ManyToManyField(League)
    def __init__(self):
        """
        Setting default year current year
        """
        today = datetime.date.today()
        today = today.timetuple()
        defaultyear = today[0]
        defaultyear = str(defaultyear)
        self.Year = defaultyear
        return self.Year

am i using the init right ... or am i missing something? or should i rename 'init' to something 'setyear' .. if yes .. then how do i call it in my django admin?

//mouse

Upvotes: 0

Views: 1167

Answers (1)

Raekkeri
Raekkeri

Reputation: 761

You could use the default parameter of the form fields, which can also be a callable. See https://docs.djangoproject.com/en/dev/ref/models/fields/#default

In which case you could rename the __init__ to setyear (and move outside of the class), and define the field with Year = models.CharField(max_length=6, default=setyear)

Upvotes: 2

Related Questions