Перейти к содержимому
Odoo Меню
  • Войти
  • Попробовать бесплатно
  • Модули
    Финансы
    • Бухгалтерия
    • Выставление счетов
    • Расходы
    • Таблицы
    • Документооборот
    • Подпись
    Продажи
    • CRM
    • Продажи
    • POS Магазин
    • POS Ресторан
    • Подписки
    • Аренда
    Вебсайты
    • Конструктор вебсайтов
    • eCommerce
    • Блог
    • Форум
    • Онлайн-чат
    • Электронное обучение
    Логистика
    • Склад
    • Производство
    • PLM
    • Закупки
    • Обслуживание
    • Качество
    Отдел кадров
    • Сотрудники
    • Подбор персонала
    • Отпуска
    • Оценка персонала
    • Реферальная программа
    • Автопарк
    Маркетинг
    • SMM
    • E-mail рассылки
    • СМС рассылки
    • Мероприятия
    • Автоматизация маркетинга
    • Опросы
    Услуги
    • Проекты
    • Табели
    • Выездной сервис
    • Поддержка
    • Планирование
    • Встречи
    Продуктивность
    • Обсуждения
    • Согласование
    • IoT
    • VoIP-телефония
    • Knowledge
    • WhatsApp
    Сторонние приложения Модуль Студия Odoo Платформа Odoo Cloud
  • Индустрии
    Розничная торговля
    • Книжный магазин
    • Магазин одежды
    • Мебельный магазин
    • Продуктовый магазин
    • Строительный магазин
    • Магазин игрушек
    Гостинично-ресторанный бизнес
    • Бар и паб
    • Ресторан
    • Фастфуд
    • Гостевой дом
    • Дистрибьютор напитков
    • Отель
    Недвижимость
    • Агентство недвижимости
    • Архитектурное бюро
    • Строительство
    • Управление недвижимостью
    • Ландшафтный дизайн
    • Товарищество собственников жилья
    Консалтинг
    • Бухгалтерская фирма
    • Партнер Odoo
    • Маркетинговое агентство
    • Юридическая фирма
    • Подбор персонала
    • Аудиторское бюро
    Производство
    • Текстиль
    • Металл
    • Мебель
    • Продукты питания
    • Пивоварня
    • Корпоративные сувениры
    Здоровье и фитнес
    • Спортивный комплекс
    • Магазин оптики
    • Фитнес-клуб
    • Велнес-центр
    • Аптека
    • Салон красоты
    Услуги
    • Специалист по бытовым услугам
    • Продажа и обслуживание IT-оборудования
    • Солнечные энергосистемы
    • Производство обуви
    • Клининг
    • Системы ОВКВ
    Прочее
    • Некоммерческая организация
    • Консалтинг в сфере устойчивого развития
    • Аренда рекламных щитов
    • Бизнес по фотосъемке
    • Прокат велосипедов
    • Реселлер программного обеспечения
    Все индустрии
  • Community
    Обучение
    • Видео уроки
    • Документация
    • Сертификация
    • Тренинг
    • Блог
    • Подкаст
    Образование и развитие
    • Образовательная программа
    • Деловая игра Scale Up!
    • Экскурсия в офис Odoo
    ПО
    • Скачать
    • Сравнить версии
    • Релизы
    Сотрудничество
    • Github
    • Форум
    • Мероприятия
    • Перевод
    • Стать партнером
    • Услуги для партнеров
    • Зарегистрировать бухгалтерскую фирму
    Услуги
    • Найти партнера
    • Найти бухгалтера
    • Встреча с экспертом
    • Услуги по внедрению
    • Отзывы клиентов
    • Поддержка
    • Обновления
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Заказать демонстрацию
  • Цены
  • Поддержка

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухгалтерия
  • Склад
  • PoS
  • Проекты
  • MRP
All apps
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Помощь

Set default duration in res_config

Подписаться

Получайте уведомления о появлении активности в этом посте

Этот вопрос был отмечен
defaultv7
3 Ответы
11634 Представления
Аватар
Lucio

I have a module that has, a creation date (of course, the day it was created) and a deadline date.

The thing is that I want to be able to set a default value to this deadline date according to the date it was created. But I want to be able to configurate this dynamically from (lets say) res_config.

e.g.

If I configured the default values in res_config to 5 days, I want the default value for the deadline date to be populated with a date 5 days ahead of the creation date.

Is this possible?

Thank you

1
Аватар
Отменить
Аватар
Lucio
Автор Лучший ответ

I managed to do this using the model ir.configure_parameter.

In res_config.py:

class my_configuration(osv.osv_memory):
    _inherit = ['res.confi.settings']
    _columns = {
       'default_deadline' : fields.integer('Days per default', help="""Help field"""),
    }
    ...
    def set_default_deadline(self, cr, uid, ids, context=None):
        config = self.browse(cr, uid, ids)
        config = config and config[0]
        val = '%s' %(config.default_deadline) or '10'
        self.pool.geet('ir.config_parameter').set_param(cr,uid, 'key_value', val)
        return True

Whit this we have created a system parameter. It is actually created as a mapping from 'key_value' to val that is a string, so we will have to cast it to the desired type when necessary. In my case, y created a function to get the deadline date in my module:

def _get_deadline_date(self, cr, uid, context=None):
    val = self.pool.get('ir.config_parameter').get_param(cr, uid, 'key_value')
    try:
        val = int(val)
    except: 
        # Just in case...
        val = 30
    return (datetime.now() + timedelta(days=val)).strftime('%Y,%m,%d')

_defaults = {
    'deadline_date': lambda s, cr, uid, c: s._get_deadline_date(self, cr, uid,     context=c),
}

Thank you, hope it helps!

1
Аватар
Отменить
Turkesh Patel (tpa)

you will need to give only default_model='' " in field ..then no req to over write get and set method ..it should work automatically..whre ever u want to set deadline there you have to get this value and set deadline

Lucio
Автор

Sorry, but I don't know what you mean with the field 'default_model'. Where is it? Actually, my idea wasn't to over write the get/set method, it is just a function to get the default value for the field (maybe the name picking was not the most accurate!). Thanks!

Аватар
Turkesh Patel (tpa)
Лучший ответ

yes this is possible using resconfig.you can define defaultdeadline field.

0
Аватар
Отменить
Lucio
Автор

I did not find the way to do that using this, because is not like I want a fix date, I want the deadline date to be, for example, 4 days after the creation date.

Can you explain to me if you know how to do this?

Аватар
Mike Telahun
Лучший ответ

To expand on Turky's comment: You don't need to write your own functions to set and get the default value. It is enough that you add the 'default_model' parameter to your column definition:

class my_configuration(osv.osv_memory):
    _inherit = ['res.config.settings']
    _columns = {
       'default_deadline' : fields.integer('Days', default_model='object.name'),
    }

For this to work correctly you will need:

  • a field named 'deadline' in your 'object.name' object
  • the column providing the default value in your res.config.settings class must begin with default_
0
Аватар
Отменить
Lucio
Автор

Good one! I did not know that! Nevertheless, the thing is that I am actually setting a numeric value, representing the numbers of days for default for a the objects of my model, so, the default value for deadline_date must be (x days + cration_date) where x is the integer that you can set in my_configuration.

Mike Telahun

As long as the field type for the default value in res.config and the field type in your object are the same. OpenERP will do the right thing.

Lucio
Автор

Yes, that's the thing in my case, they where not! Because I wanted to set a date "on the fly", adding a time delta to the creation date. Setting a date as default will just set in all records the field with the value in res.config. Hope I am not missing something here!

Mike Telahun

I'm not sure if I understand correctly, but here goes: In your main object you should have three fields: begin_date, deadline_date and deadline_delta. The begine_date and deadline_date fields are date fields and deadline_delta would be an integer field. Then in res.config you would have a field called default_deadline_delta, which is an integer. Then in your main object you would have an onchange method on the begin_date field, which when triggered would change the value of deadline_date by adding deadline_delta to begin_date. I hope I have correctly understood what you want to do.

Lucio
Автор

Yes, the answer you are giving me fit my requirements perfectly! The thing is that, by doing so, I would create a field in the database for every record of my model, that is to be filled on creation time and never to be modified again. (If you want to change the deadline_date you should change it directly not changing the deadline_delta). Thanks for your concern! :D

Не оставайтесь в стороне – присоединяйтесь к обсуждению!

Создайте аккаунт сегодня, чтобы получить доступ к эксклюзивным функциям и стать частью нашего замечательного сообщества!

Регистрация
Похожие посты Ответы Просмотры Активность
How to send a default model_id in a view? (old api)
default v7
Аватар
0
апр. 15
4766
Add an item passing relation as default?
default create v7
Аватар
0
мар. 15
4181
Default values for Users Решено
default v7 location
Аватар
Аватар
1
февр. 24
14495
How to set default time for date_stop in calendar view?
calendar default v7
Аватар
Аватар
1
мар. 15
9679
How to calculate new function field on module update? Решено
default v7 update
Аватар
Аватар
1
мар. 15
8488
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • Github
  • Runbot
  • Перевод
Услуги
  • Хостинг Odoo.sh
  • Поддержка
  • Обновление
  • Индивидуальные решения по доработке
  • Образование
  • Найти бухгалтера
  • Найти партнера
  • Стать партнером
О нас
  • Наша компания
  • Активы бренда
  • Cвяжитесь с нами
  • Вакансии
  • Мероприятия
  • Подкаст
  • Блог
  • Клиенты
  • Правовые документы • Конфиденциальность
  • Безопасность
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo – это набор бизнес-модулей с открытым исходным кодом, который закроет все потребности вашей компании: CRM, E-commerce, Бухгалтерия, Склад, POS, управление проектами и др.

Odoo сочетает в себе простоту использования и полную интеграцию всех бизнес-процессов в одной системе.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now