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

Make a field non-editable after Save

Подписаться

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

Этот вопрос был отмечен
7 Ответы
20257 Представления
Аватар
aci aisha

Friends,

I have a field field_type.Its a many2one.I have to make it non-editable after save it.

Ex:When i create a file 1st time i set field_type as "Trademark"..

     Then when i edit it the field_type should be read only

Thanks...

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

Redefine id as an integer field, put the id field in the view and use it in the attrs: attrs="{'readonly':[('id','>', 0)]}"

7
Аватар
Отменить
aci aisha
Автор

thanks ivan,but need som clarification

Ivan

Sure @aci, what clarification do you need?

aci aisha
Автор

what u mean by id?

Ivan

When you define a model, Odoo/OpenERP will always add 5 additional columns (in some of the codes they call it Magic Columns: id, create_uid, create_date, write_date, write_uid) which will be controlled by ORM. id is the Database ID which will be the unique identifier of the record and Primary Key of the table representing the record and id is only assigned after the record is saved for the first time. It is implemented as serial in PostgreSQL and hence will start with 1 and continue until limit is reached, never recycled. The create_ pairs will record who and when the record is created (_uid will be a FK to res.users and _date is a timestamp field), while write_ pair will record who and when the record is updated last via ORM. Unfortunately you cannot just use the column 'id' without defining it in _columns. That's why I say you need to re-define the column first as an integer column.

aci aisha
Автор

Ya Allah,,Confused!!!

aci aisha
Автор

Ivan plz help

Ivan

Have you tried the solution? Create an integer field, call it 'id', include it in the view, and use it in attrs?

aci aisha
Автор

Ivan,try as u told,but the following error occured... Uncaught Error: Unknown field id in domain [["id",">",0]]

Ivan

Have you include the 'id' field in the view?

aci aisha
Автор

yes, 'id' : fields.integer('ID'),

Ivan

That is not the view @aci. The view is defined in XML, part of which you put in your answer.

aci aisha
Автор

Great Ivan..U R BRILLIANT!!!!

Nebil Aydi

you are genius Mr Ivan

Stoian Razvan

Thank you!

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

Add a boolean field in the py fiel and add the field in the view and make it as invisible,then use the following code:

<field name="dummy_field" invisible="1" />

<field name="field_type"  attrs="{'readonly':[('dummy_field','=', True)]}" on_change="onchange_file_type(file_type)" />

In the onhange method,check if the field_type is true,then make the boolean (dummy_field) as true

else False

 

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

as empiro tech said.. add a state field like draft...

whenever you create the record it should be set to draft...

like _defaults={

        'state':'draft',

                          }

 

then in field set attrs="{'readonly':[('state','=','draft')]}"

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

This would be wery unprqactical... name state is reserved for states, and if you add more states , while using your code, the field would be readonly ONLY in draft state.... ( other models like account invoice , sales order etc...use reverse logic,,, 'readonly':[('state','!=',draft)]...

Anand

functionally it will right.. but conceptually wrong may be...

Anand

may be dummy field whic would do like this...

Аватар
Amit Muchhala
Лучший ответ

You can do one thing:

First one in xml side:


Here id is compared with 0. If the record is created, it will have an integer id which will be greater than 0. And as per your requirement, when you are creating the record, the field will be editable. But when you save the record, id will be generated and the field will be readonly.1

0
Аватар
Отменить
Аватар
aci aisha
Автор Лучший ответ

Thank you Every1 for ur co-operation...

Friends,

When i use the following code it works,

                    <field name="file_type"  attrs="{'readonly':[('file_type','!=', False)]}" on_change="onchange_file_type(file_type)" /> 

That is when i select 1 value in file_type it becomes read only...

But when i try to save the file it cause the following error...!!

 

Odoo Warning

Integrity Error

The operation cannot be completed, probably due to the following:
- deletion: you may be trying to delete a record while other records still reference it
- creation/update: a mandatory field is not correctly set

[object with reference: file_type - file.type]

I also try this,,

    _columns = {
                'name' : fields.char('File No', readonly=True),
                #'file_type': fields.selection((('Trademark Registeration','Trademark Registeration'), ('Company Registeration','Company Registeration')),'File Type'),        
                'file_type': fields.many2one('file.type.details','File Type',required=True),
                'seq_id':fields.related('file_type','seq_id',type='char',string='Sequence ID'),        
                'application_no' : fields.char('Application No'),
                'classification_no' : fields.many2one('classification.details', 'Classification Number'),
                'classi_name' : fields.related('classification_no','classification_name',type='char',string= 'Classification Name'),
                'remarks' : fields.text('Remarks'),
                'file_status_id' : fields.many2one('file.status', 'Status', required=False),
                'a' : fields.char('a'),
                }
    _defaults={
                #'file_type' : _get_file_type
                'a' : 'a'

&

                    <field name="file_type"  attrs="{'readonly':[('a','=', 'a')]}" on_change="onchange_file_type(file_type)" /> 

But i cause the following error,

Error: Unknown field a in domain [["a","=","a"]]

 

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

See my comment in @Bole's answer.

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

The simplest way to do it is to define readonly state on the ffield ITSELF:.. in xml view definition... like:

<field name="your_field_name" attrs="{'readonly':[('your_field_name','=',False)]}" />

beware this will only allow to select value ONCE, and if you select wrong value, you need a mechanism to change it (just in case of error) . Such mechanism can be a wizard (allowerd for specific group  of users .. or something simmilar... )

Using field state to determine readonly state is most usual way to do it, but then the field remains in RW state until whole document changes state ... 

hop it helps..

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

how set wizard?

Ivan

@Bole, I think that approach would not work. Once the field is populated, then it will be made readonly and hence the value would not be stored in the database. So, when the record is pulled up again, it would be empty and editable.

Аватар
Emipro Technologies Pvt. Ltd.
Лучший ответ

Try to add some kind of "state" and based on that you can make id readonly.

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

state is a field??

Emipro Technologies Pvt. Ltd.

yes... ofcourse.. it is a field. Try looking the examples in sale order, purchase order, you will get better idea.

aci aisha
Автор

But if i add a state field,Have i enter values there?

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

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

Регистрация
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • 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