-1

I generate xls file from odoo, the code works in my laptop but in server machine it doesn't i tried the both commands:

1- sudo chmod -R 777 /usr/local/lib/python3.6/

2-sudo chown -R 777 /odoo/

but nothing has changed

Thanks for help

File code of module dangerous.product.wizard

# -*- coding:utf-8 -*-
# here is the file of generation xls file 
from datetime import timedelta
import xlwt
from odoo import models, fields, api, _


class LiberationPfWizard(models.TransientModel):
    _name = 'dangerous.product.wizard'

    date_from = fields.Date(string='From', required=True, default=fields.Date.today().replace(month=1, day=1))
    date_to = fields.Date(string='To', required=True, default=fields.Date.today().replace(month=12, day=31))
    product_ids = fields.Many2many('product.product',
                                   string="Products list",
                                   default=lambda self: self.env['product.product'].search([('is_dangerous', '=', True)]))

    @api.multi
    def print_report_xls(self):
        workbook = self.sudo().create_workbook()
        return self.env['report.xls'].report_action(workbook, _('Dangerous product Excel'))

    def get_report_lines(self):
        lines = []
        product_ids = self.env['product.product'].with_context(dict(self.env.context, to_date=self.date_from)).search([
            ('id', 'in', self.product_ids.ids)
        ])
        for product_id in product_ids:
            data = {
                'product_name': product_id.name,
                'product_technical_description': product_id.technical_description,
                'onu_number': product_id.onu_number,
            }
            moves = self.env['stock.move'].search([
                ('state', '=', 'done'),
                ('product_id', '=', product_id.id),
                ('date', '>=', self.date_from),
                ('date', '<', self.date_to + timedelta(days=1)),
            ])
            in_qty = sum(moves.filtered(
                lambda move: move.location_id.usage in ['customer', 'supplier', 'inventory'] and move.location_dest_id.usage == 'internal'
            ).mapped('quantity_done'))
            out_qty = sum(moves.filtered(
                lambda move: move.location_id.usage == 'internal' and move.location_dest_id.usage in ['production', 'customer', 'supplier', 'inventory']
            ).mapped('quantity_done'))
            data['initial_stock'] = product_id.qty_available
            data['in_qty'] = in_qty
            data['out_qty'] = out_qty
            lines.append(data)
        return lines

    def create_workbook(self):
        lines = self.get_report_lines()

        date_from = self.date_from
        date_to = self.date_to
        workbook = xlwt.Workbook()
        xlwt.add_palette_colour("teal", 0x21)
        workbook.set_colour_RGB(0x21, 0, 128, 128)
        xlwt.add_palette_colour("magenta", 0x22)
        workbook.set_colour_RGB(0x22, 224, 17, 95)
        xlwt.add_palette_colour("light_grey", 0x23)
        workbook.set_colour_RGB(0x23, 222, 222, 222)

        colorized = xlwt.easyxf(
            'font:height 220,bold True;pattern: pattern solid, fore_colour light_grey;align: horiz center, vert center; '
            'border: left thin,right thin,top thin,bottom thin')
        value = xlwt.easyxf(
            'font:height 220;align: horiz center, vert center;border: left thin,right thin,top thin,bottom thin')
        teal = xlwt.easyxf(
            'font:height 220,colour white,bold True;pattern: pattern solid, '
            'fore_colour teal;align: horiz center, vert center; '
            'border: left thin,right thin,top thin,bottom thin')
        magenta = xlwt.easyxf(
            'font:height 220,colour white,bold True;pattern: pattern solid, '
            'fore_colour magenta;align: horiz center, vert center; '
            'border: left thin,right thin,top thin,bottom thin')
        sheet = workbook.add_sheet(_('Liberation PF'))

        sheet.write_merge(1, 1, 0, 6, _('Monthly Declaration of Dangerous Raw Materials'), magenta)
        sheet.write_merge(2, 2, 0, 6, _('FROM %s TO %s') % (str(date_from), str(date_to)), teal)
        sheet.write(3, 0, _('NAME'), colorized)
        sheet.write(3, 1, _('TECHNICAL DESCRIPTION'), colorized)
        sheet.write(3, 2, _('N° ONU-CAS-CEE-EINCS'), colorized)
        sheet.write(3, 3, _('STOCK AT %s') % str(self.date_from - timedelta(days=1)), colorized)
        sheet.write(3, 4, _('ENTERED'), colorized)
        sheet.write(3, 5, _('QUANTITY USED'), colorized)
        sheet.write(3, 6, _('BALANCE AT %s') % str(self.date_to), colorized)
        l = 4
        for line in lines:
            sheet.write(l, 0, line.get('product_name'), value)
            sheet.write(l, 1, line.get('product_technical_description') or '/', value)
            sheet.write(l, 2, line.get('onu_number') or '/', value)
            sheet.write(l, 3, line.get('initial_stock'), value)
            sheet.write(l, 4, line.get('in_qty'), value)
            sheet.write(l, 5, line.get('out_qty'), value)
            sheet.write(l, 6, abs(line.get('initial_stock') + line.get('in_qty') - line.get('out_qty')), value)
            l += 1

        sheet.col(0).width = 256 * 48
        sheet.col(1).width = 256 * 72
        sheet.col(2).width = 256 * 48
        for i in range(3, 7):
            sheet.col(i).width = 256 * 28
        return workbook

File code of module report.xls Error in server machine only in line line 21, in report_action workbook.save(filename)

# -*- coding: utf-8 -*-

import base64

from odoo import models, fields, api, _
from odoo.exceptions import UserError


class ReportXLS(models.TransientModel):
    _name = "report.xls"
    _description = "Report xls"

    file_name = fields.Binary('Excel Report', readonly=True, attachment=True)
    data = fields.Binary('File', readonly=True)
    name = fields.Char('Filename', readonly=True)

    @api.model
    def report_action(self, workbook, filename=_("XLS REPORT")):
        if workbook:
            filename = '%s.%s' % (filename, 'xls')
            workbook.save(filename)
            file = open(filename, "rb")
            file_data = file.read()
            out = base64.encodebytes(file_data)
            record = self.env['report.xls'].create({
                'file_name': out,
                'data': out,
                'name': filename
            })
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'report.xls',
                'view_mode': 'form',
                'view_type': 'form',
                'res_id': record.id,
                'target': 'new',
            }
        raise UserError(
            _('There is no XLS File to print !')
        )

Here the full error's message

Erreur: Odoo Server Error

Traceback (most recent call last): File "/odoo/odoo-server/odoo/http.py", line 656, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/odoo/odoo-server/odoo/http.py", line 314, in _handle_exception raise pycompat.reraise(type(exception), exception, sys.exc_info()[2]) File "/odoo/odoo-server/odoo/tools/pycompat.py", line 87, in reraise raise value File "/odoo/odoo-server/odoo/http.py", line 698, in dispatch result = self._call_function(**self.params) File "/odoo/odoo-server/odoo/http.py", line 346, in _call_function return checked_call(self.db, *args, **kwargs) File "/odoo/odoo-server/odoo/service/model.py", line 97, in wrapper return f(dbname, *args, **kwargs) File "/odoo/odoo-server/odoo/http.py", line 339, in checked_call result = self.endpoint(*a, **kw) File "/odoo/odoo-server/odoo/http.py", line 941, in call return self.method(*args, **kw) File "/odoo/odoo-server/odoo/http.py", line 519, in response_wrap response = f(*args, **kw) File "/odoo/odoo-server/addons/web/controllers/main.py", line 966, in call_button action = self._call_kw(model, method, args, {}) File "/odoo/odoo-server/addons/web/controllers/main.py", line 954, in _call_kw return call_kw(request.env[model], method, args, kwargs) File "/odoo/odoo-server/odoo/api.py", line 749, in call_kw return _call_kw_multi(method, model, args, kwargs) File "/odoo/odoo-server/odoo/api.py", line 736, in _call_kw_multi result = method(recs, *args, **kwargs) File "/odoo/custom/lsee/quality_pharm_report/wizard/dangerous_product_balance_wizard.py", line 20, in print_report_xls return self.env['report.xls'].report_action(workbook, _('Dangerous product Excel')) File "/odoo/custom/lsee/report_xls/wizard/report_xls.py", line 21, in report_action workbook.save(filename) File "/usr/local/lib/python3.6/dist-packages/xlwt/Workbook.py", line 710, in save doc.save(filename_or_stream, self.get_biff_data()) File "/usr/local/lib/python3.6/dist-packages/xlwt/CompoundDoc.py", line 262, in save f = open(file_name_or_filelike_obj, 'w+b') PermissionError: [Errno 13] Permission denied: 'Produits dangereux Excel.xls'

MOHAMED
  • 101
  • 2
  • 10

1 Answers1

0

I would stick to the solution Odoo itself is using for its reports or export files: use /tmp as temporarily (pun intended) file directory. On "normal" or "usual" server configurations, this directory can be used by nearly all applications without thinking about file access.

So you have to change the path your custom module is using for creating the Excel file. (Can't help further, because you didn't share your code)

CZoellner
  • 13,553
  • 3
  • 25
  • 38
  • The `filename` is just a relative path in context of execution. Just add the tmp directory and make it a absolute filepath -> `'/tmp/' + filename`. – CZoellner Nov 21 '19 at 17:30