-1

I want to get the day name based on the date selected from the fields. I have the code as below:

from datetime import datetime, date
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
import calendar

class HrPublicHolidayHolidays(models.Model):
    _name = 'hr.public.holiday.holidays'
    _description = 'Public Holidays Dates'

    name = fields.Char('Holiday Name', required=True)
    date = fields.Date('Holiday Date', required=True)
    date_day = fields.Char('Day')
    year_id = fields.Many2one('hr.public.holiday', 'Calendar Year', required=True)
    variable = fields.Boolean('Date may change')

    @api.onchange('date')
    def _get_day_of_date(self):
        for r in self:
            selected = fields.Datetime.from_string(r.date)
            r.date_day = calendar.day_name[selected.weekday()]

Then when I run the code, when I click on the add an item enter image description here

After I clicked the button it shows me the error result: enter image description here

But if I try to select the date, it will show the day of the date that I've selected like: enter image description here

So basically the code will run, but the error just keeps on showing and I have no idea why.

Dharman
  • 30,962
  • 25
  • 85
  • 135

1 Answers1

0

First, get the current date by default, e.g.:

date = fields.Date(string='Date', default=fields.Date.context_today, required=True)

after that write this bellow function to get the name of the day

@api.multi
@api.depends('date')
def _get_day(self):
    self.day = self.date and (datetime.strptime(self.date, '%Y-%m-%d').date()).strftime('%A') or ''
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • odoo has own methods like fields.Datetime.from_string() if you get the date from the odoo Database. Probably uses Datetime as well but also probably more secure in case of future upgrades. – Mangocherry Aug 23 '19 at 17:10