Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateField 'str' object has no attribute 'year'

Tags:

python

django

When trying to access the year and month attributes of my DateField objects I am getting the error

AttributeError: 'str' object has no attribute 'date'.

I thought that DateField objects were saved as Python Datetime objects instead of strings.

Here is the models.py:

class MonthControlRecord(models.Model):
    STATUS_CHOICES = (
        (0, 'Open'),
        (1, 'Locked'),
        (2, 'Closed'),
    )
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    first_day_of_month = models.DateField()
    status = models.IntegerField(choices=STATUS_CHOICES, default=0)

    @property
    def get_year_month(self):
        return self.first_day_of_month.year, self.first_day_of_month.month

    def __str__(self):
        return self.employee, self.first_day_of_month

and the tests.py:

employee = Employee.objects.get(staff_number="0001")
mcr = MonthControlRecord(employee=employee, first_day_of_month="2015-12-01")
mcrYearMonth = mcr.get_year_month

and the error:

Traceback (most recent call last):
  File "/Users/James/Django/MITS/src/timesheet/tests.py", line 87, in test_new_month_control_record
    mcrYearMonth = mcr.get_year_month
  File "/Users/James/Django/MITS/src/timesheet/models.py", line 54, in get_year_month
    return self.first_day_of_month.year, self.first_day_of_month.month
AttributeError: 'str' object has no attribute 'year'
like image 773
ijames55 Avatar asked Dec 07 '15 10:12

ijames55


1 Answers

In your test, you're setting the date as a string:

mcr = MonthControlRecord(employee=employee, first_day_of_month="2015-12-01")

Try setting it as a date:

your_date = datetime.date(2015, 12, 1)
mcr = MonthControlRecord(employee=employee, first_day_of_month=your_date)
like image 53
César García Tapia Avatar answered Oct 06 '22 00:10

César García Tapia