You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo 16中上传.doc文件时如何在对话框筛选Word格式文件?

解决Odoo中many2many_binary控件限制仅选择Word文档的问题

要实现文件选择对话框只筛选*.doc(含*.docx)格式文件,需要从前端控件限制和后端验证两方面入手:

一、自定义前端Widget限制文件类型

系统文件选择对话框的筛选规则由HTML输入框的accept属性控制,需继承原many2many_binary widget并修改该属性:

  1. 创建自定义JS文件(示例路径:static/src/js/many2many_binary_word.js):
odoo.define('your_module.many2many_binary_word', function (require) {
    "use strict";

    var Many2ManyBinaryWidget = require('web.Many2ManyBinaryWidget');
    var fieldRegistry = require('web.field_registry');

    var Many2ManyBinaryWord = Many2ManyBinaryWidget.extend({
        _createFileInput: function () {
            var input = this._super.apply(this, arguments);
            // 限制仅允许选择doc和docx格式文件
            input.attr('accept', '.doc,.docx');
            return input;
        },
    });

    fieldRegistry.add('many2many_binary_word', Many2ManyBinaryWord);

    return Many2ManyBinaryWord;
});
  1. 在模块的__manifest__.py中注册该JS文件:
{
    # 其他配置项...
    'assets': {
        'web.assets_backend': [
            'your_module/static/src/js/many2many_binary_word.js',
        ],
    },
}
  1. 在视图中替换为自定义Widget:
<field name="word_file" widget="many2many_binary_word"/>

二、后端添加格式验证(可选但推荐)

为避免用户通过其他渠道上传不符合要求的文件,在模型中添加字段约束:

from odoo import models, api
from odoo.exceptions import ValidationError

class YourModel(models.Model):
    _name = 'your.model.name'
    # 原字段定义保持不变
    word_file = fields.Many2many('ir.attachment', 'document_ref_table_1', 'document_id_1', 'ir_attachment_id_1', string="File Word", required=True)

    @api.constrains('word_file')
    def _validate_word_file_format(self):
        for record in self:
            for attachment in record.word_file:
                if not attachment.name.lower().endswith(('.doc', '.docx')):
                    raise ValidationError(f"文件「{attachment.name}」不是有效的Word文档,请上传.doc或.docx格式文件")

内容的提问来源于stack exchange,提问作者Cris Tuan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 15:36:10