Перейти к содержимому
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
Об этом форуме
Помощь

How to define custom settings on configuration view?

Подписаться

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

Этот вопрос был отмечен
configurationodoo8.0
8 Ответы
13564 Представления
Аватар
Yenthe Van Ginneken (Mainframe Monkey)

Hi guys,

I've created a new view which should always only allow one record, so I've made a view just like under Settings > Configuration.
1) Create a menu item

 <menuitem id="menu_tech_settings_screen"
                action="technical_details_odoo_installer_action" parent="server_main_menu"
                sequence="30"/>

2) Add an act_window behind it:

 <record id="technical_details_odoo_installer_action" model="ir.actions.act_window">
            <field name="name">Configure settings</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">odoo.environment.technical.settings</field>
            <field name="view_id" ref="configure_technical_settings_odoo_installer"/>
            <field name="view_mode">form</field>
            <field name="target">inline</field>
        </record>

3) Create a view just like under Settings > Configuration > General Settings:

 <record id="configure_technical_settings_odoo_installer" model="ir.ui.view">
            <field name="name">Technical configuration</field>
            <field name="model">odoo.environment.technical.settings</field>
            <field name="arch" type="xml">
                <form string="Configure Sales" class="oe_form_configuration">
                    <header>
                        <button string="Apply" type="object" name="execute" class="oe_highlight"/>
                        or
                        <button string="Cancel" type="object" name="cancel" class="oe_link"/>
                    </header>
		<div name="configuration">
		    <group>
		        <field name="my_custom_field"/>
		    </group>
		</div>
		</form>
	    </field>
	</record>

The view is being rendered fine but I'm now wondering how to proceed. How exactly can I store the new value when a user clicks on the Apply button? There should only be one record at all times and this is used to configure the rest on. I've inherited res.config.settings, created my own model and I have a get and set function for this. Example:

 class my_custom_class(models.Model):
    _name = 'my.custom.model'
    _inherit = 'res.config.settings'
    odoo_username = fields.Char('Ubuntu users password',help='Please fill in the password for the Ubuntu user that runs this Odoo. This password is needed to automatically install a new Odoo server through a shell script. Installing a new Odoo needs sudo rights!',required=True)

    def get_default_username(self, cr, uid, fields, context=None):
        odoo_username=self.pool.get('my.custom.model').browse(cr, uid, uid, context=context).odoo_username
        return {'odoo_username': odoo_username}

    def set_default_username(self, cr, uid, ids, context=None):
        config = self.browse(cr, uid, ids[0], context)
        new_odoo_username=config.odoo_username
        self.pool.get('my.custom.model').write(cr, uid, uid, {'odoo_username': new_odoo_username})

The problem here is that this will still create a new record every time and I'm not sure if this is the correct behaviour for this type of view either.

Thanks,
Yenthe

1
Аватар
Отменить
Gautam

Hello yenthe,

I am also facing the same issue in odoo 12. So did you find any solution for that?

Аватар
Tarek Mohamed Ibrahim
Лучший ответ

I checked your code, but since I don't have much experience with inheriting res.config.settings I can't judge if this is not appropriate, or find a bug in it. 

Instead, I came up with a different solution, you don't need to inherit the settings class, you can create a new class for your setup purpose.


Code is below:

This is the class:

class my_custom_class(osv.osv):
    _name = 'my.custom.class'
    _description = 'my_custom_class'
    _columns = {
        'odoo_username':fields.char(string='odoo_username',),
        }
my_custom_class()

 

This is the view, along with the menu and the action

<record id="my_custom_class_view" model="ir.ui.view">
<field name="name">my.custom.class.view</field>
<field name="model">my.custom.class</field>
<field name="arch" type="xml">
<form string="my custom class" create="false" delete="false">
<field name="odoo_username" string="Odoo Username"/>
</form>
</field>
</record>
<record id="act_my_custom_class_view" model="ir.actions.act_window">
<field name="name">my.custom.class.view</field>
<field name="res_model">my.custom.class</field>
<field name="view_type">form</field>
<field name="view_mode">form</field>
</record>
<!-- the following is a one record as initial data -->
<record id="my_custom_class_only_one_record" model="my.custom.class">
<field name="odoo_username">"test odoo user name"</field>
</record>

<menuitem action="act_my_custom_class_view" id="menu_act_my_custom_class_view" parent="some_module.some_parent_id" sequence="30"/>

Note that I tagged the view form with 

create="false" delete="false" 

so, no one can add or delete records to this view

I also furnished this class with one data record with initial value(s) user can starts with.

I hope this will help until we get some more experience with the res.config.settings, which is the standard for this purpose.

1
Аватар
Отменить
Yenthe Van Ginneken (Mainframe Monkey)
Автор

Thanks for your answer Tarek! I gave you a +1 since its another option and it would work but I honestly do not think this is the ideal way to do it.

Tarek Mohamed Ibrahim

I agree with you that this is not the ideal way, and for that I said that "I hope this will help until we get some more experience with the res.config.settings". This is a workaround, I do that when I'm pressed in time and need to deliver to the customer. When got the idea and there is an area to enhance, I provide the customer with the standard solution

Rohit Pandey

Hi @Yenthe, can you tell me how you do this?

Аватар
Anil Kesariya
Лучший ответ

HI Yenthe,

These solution might helps you.

1) Override create method of new model and search all the records created with new model and check length if  already having 1 than either raise warning or just return false instead of retuning result of super. this will stop user to creating more than 1 record in new model.

2) Apply create="false" and edit="false" in both tree and form view of new model. and create of actions todo with trigger your actions in that case open the form view in edit mode which will trigger once you install or upgrade module after adding this feature which will create record as you want than . after that user will not able to add any record inside as create & edit is false already.

Hope this might help.

Rgds,

Anil.




0
Аватар
Отменить
Yenthe Van Ginneken (Mainframe Monkey)
Автор

Thanks for your answer Anil! While this is a way and it will work I can't imagine that this is the way to go. Sounds like a lot of hassle and code for such a little functionality.

Anil Kesariya

@yenthe: If you don't want to show that record that user than don't create any action or view for that. Just create record in back end by automated actions as simple as that. But if you want to show that records in UI with different view and model than of course you have to create views and action for it.

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

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

Регистрация
Похожие посты Ответы Просмотры Активность
how to add landed cost per product, such as adding Customs Tariffs fee on product and other products don't have Customs Tariffs??
configuration
Аватар
0
дек. 25
14
Installation Odoo 17 Community
configuration
Аватар
Аватар
1
нояб. 25
1123
Multiple trading names under one legal entity
configuration
Аватар
0
нояб. 25
45
Odoo Lot Location Missing After Partial Stock Move
configuration
Аватар
0
нояб. 25
3
Adding a new security group to an existing module
configuration
Аватар
0
нояб. 25
6
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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