İçereği Atla
Odoo Menü
  • Portal
  • Ücretsiz deneyin
  • Uygulamalar
    Finans
    • Muhasebe
    • Faturalama
    • Masraf Yönetimi
    • Elektronik Çizelge (BI)
    • Belgeler
    • İmza
    Satış
    • Müşteri İlişkileri Yönetimi (CRM)
    • Satış
    • Satış Noktası Mağaza
    • Satış Noktası Restoran
    • Abonelikler
    • Kiralama
    Web Sitesi
    • Web Sitesi Oluşturucu
    • eTicaret
    • Blog
    • Forum
    • Canlı Sohbet
    • eÖğrenme
    Tedarik Zinciri
    • Envanter
    • Üretim
    • Ürün Yaşam Döngüsü Yönetimi
    • Satın Alma
    • Bakım
    • Kalite
    İnsan Kaynakları
    • Çalışanlar
    • İşe Alım
    • İzin
    • Değerlendirme
    • Referans
    • Filo Yönetimi
    Pazarlama
    • Sosyal Medyada Pazarlama
    • E-posta ile Pazarlama
    • SMS ile Pazarlama
    • Etkinlikler
    • Pazarlama Otomasyonu
    • Anket
    Hizmetler
    • Proje Yönetimi
    • Çalışma Çizelgeleri
    • Saha Hizmeti
    • Yardım Masası
    • Planlama
    • Randevular
    Verimlilik
    • Sohbet
    • Onay
    • Nesnelerin İnterneti
    • VoIP
    • Bilgi Bankası
    • WhatsApp
    Üçüncü taraf uygulamalar Odoo Stüdyo Odoo Bulut Platformu
  • Sektörler
    Perakende satış
    • Kitapçı
    • Giyim Mağazası
    • Mobilya Mağazası
    • Gıda Marketi
    • Hırdavat Dükkanı
    • Oyuncak Dükkanı
    Gıda ve Konaklama
    • Bar ve Pub
    • Restoran
    • Fast Food Restoranı
    • Konuk Evi
    • İçecek Distribütörü
    • Otel
    Gayrimenkul
    • Emlak Acentesi
    • Mimarlık Firması
    • İnşaat
    • Emlak Yönetimi
    • Bahçe Tasarımı
    • Mülk Sahipleri Derneği
    Uzmanlık
    • Muhasebe Firması
    • Odoo Partner
    • Pazarlama Ajansı
    • Hukuk Firması
    • Yetenek Kazanımı
    • Denetim ve Belgelendirme
    Üretim
    • Tekstil
    • Metal
    • Mobilyalar
    • Gıda
    • Bira fabrikası
    • Kurumsal Hediye
    Sağlık ve Spor
    • Spor Kulübü
    • Optik Mağazası
    • Fitness Merkezi
    • Sağlıklı Yaşam Merkezi
    • Eczane
    • Kuaför Salonu
    Ticaret
    • Tamirci
    • BT Donanım & Destek
    • Güneş Enerjisi Sistemleri
    • Ayakkabı İmalatçısı
    • Temizlik Hizmetleri
    • HVAC Hizmetleri
    Diğerleri
    • Kar Amacı Gütmeyen Kuruluş
    • Çevre Ajansı
    • Reklam Panosu Kiralama
    • Fotoğrafçılık
    • Bisiklet Kiralama
    • Yazılım Bayisi
    Tüm Sektörlere Göz Atın
  • Topluluk
    Öğrenim
    • Eğitim Araçları
    • Dokümantasyon
    • Sertifikasyonlar
    • Eğitim Etkinlikleri
    • Blog
    • Podcast
    Eğitim ve Gelişim
    • Eğitim Programı
    • Scale Up! İşletme Oyunu
    • Odoo'yu Ziyaret Edin
    Yazılım
    • İndirin
    • Sürümleri Kıyaslayın
    • Sürümler
    İş Birliği
    • Github
    • Forum
    • Etkinlikler
    • Çeviriler
    • Partner Olun
    • Partnerler için Hizmetler
    • Muhasebe Firmanızı Kaydettirin
    Hizmetler
    • Partner Bulun
    • Muhasebeci Bulun
    • Bir danışmanla görüşün
    • Kurulum Hizmetleri
    • Müşteri Referansları
    • Destek
    • Sürüm Yükseltme
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Demo randevusu alın
  • Fiyatlandırma
  • Yardım

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

  • Müşteri İlişkileri Yönetimi
  • e-Commerce
  • Muhasebe
  • Envanter
  • PoS
  • Proje Yönetimi
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiketler (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiketler (View all)
odoo accounting v14 pos v15
About this forum
Yardım

Press a button and download a file, how?

Abone Ol

Get notified when there's activity on this post

Bu soru işaretlendi
pythonfiledownloadodooV8
6 Cevaplar
68882 Görünümler
Avatar
E.M.

I would like to make Odoo download a file (from a text string for example) when a button is clicked. Is there any example I could start with or can anyone provide a basic code structure for downloading a file?

Thanks

3
Avatar
Vazgeç
OdooBot
thanks that is great

On Sun, Mar 17, 2019 at 6:39 PM Oleksandr Komarov <komarovalea@gmail.com> wrote:

The easiest way to do this is using Transient model:

1. Create Transient Model with Binary field:

class GetFile(models.TransientModel):

_name = 'save.file.wizard'file_name = fields.Char('File name', readonly=True)

my_file = fields.Binary('File data', readonly=True,

help='File(jpg, csv, xls, exe, any binary or text format)')

2. Create Button on the Form in any Model(for example 'some_model'):

<button name="save_to_file" string="Save to file" type="object"

class="oe_stat_button oe_read_only" icon="fa-download"/>

3. Create function 'save_to_file' in model 'some_model':

@api.multi

def save_to_file(self):

some_data = 'This is data of file as String type'

my_file = self.env['save.file.wizard'].create({

'file_name': 'my-file.txt',

'xml_file': base64.b64encode(str.encode(xml_text)),

})

return {

'name': _('Download File'),

'res_id': my_file.id,

'res_model': 'o1c.save.conf',

'target': 'new',

'type': 'ir.actions.act_window',

'view_id': self.env.ref('my_module_name.save_file_wizand_view_done').id,

'view_mode': 'form',

'view_type': 'form',

}

4. Create Form for downloading files:

<record id="save_file_wizand_view_done" model="ir.ui.view">

<field name="name">save.file.wizard.form</field>

<field name="model">save.file.wizard</field>

<field name="arch" type="xml">

<form string="File download">

<group cols="2">

<div>

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

<label string="The file has been successfully generated." />

<field name="my_file" filename="file_name" nolabel="1" />

</div>

</group>

<footer>

<button special="cancel" string="Close" type="object" />

</footer>

</form>

</field>

</record>

That is all.

Sent by Odoo S.A. using Odoo.

Sehrish

Try this: http://learnopenerp.blogspot.com/2020/06/write-binary-data-nto-zip-file-and-downlaod-it-on-button-click-in-odoo.html

Avatar
Emipro Technologies Pvt. Ltd.
En İyi Yanıt

Hi,

We at Emipro, got this question numerous times from different Odoo developers. So here I am giving the step by step guidance how to do this.

Here all my code is in V8.

  • Create a method inside your regular model and return URL. 

For example, 

 @api.multi 
def get_stock_file(self):
    return {
            'type' : 'ir.actions.act_url',
            'url': '/web/binary/download_document?model=wizard.product.stock.report&field=datas&id=%s&filename=product_stock.xls'%(self.id),
            'target': 'self',
}

Here I have returned URL with model and some info. Now in next step i will catch that URL to a controller method.

( just like file you can see in /web/controllers/main.py )

  • Make a controller class and catch that url and do process for download excel file.

from openerp import http
from openerp.http import request
from openerp.addons.web.controllers.main import serialize_exception,content_disposition
import base64
class Binary(http.Controller):
@http.route('/web/binary/download_document', type='http', auth="public")
@serialize_exception
def download_document(self,model,field,id,filename=None, **kw):
    """ Download link for files stored as binary fields.
    :param str model: name of the model to fetch the binary from
     :param str field: binary field
     :param str id: id of the record from which to fetch the binary
    :param str filename: field holding the file's name, if any
    :returns: :class:`werkzeug.wrappers.Response`
    """
    Model = request.registry[model]
    cr, uid, context = request.cr, request.uid, request.context
    fields = [field]
    res = Model.read(cr, uid, [int(id)], fields, context)[0]
    filecontent = base64.b64decode(res.get(field) or '')
    if not filecontent:
         return request.not_found()
    else:
        if not filename:
            filename = '%s_%s' % (model.replace('.', '_'), id)
            return request.make_response(filecontent,
                            [('Content-Type', 'application/octet-stream'),
                             ('Content-Disposition', content_disposition(filename))])

In above method I have got the ID from url and then applied some calculation and return the http response from request. Whatever values I have passed from wizard to controller method, I will get them on controller method.

( See below, I have passed model, field, id and filename from url )

/web/binary/download_document?model=wizard.product.stock.report&amp;field=datas&amp;id=%s&amp;filename=product_stock.xls
def download_document(self,model,field,id,filename=None, **kw):

I have returned Excel file but you can return any kind of file and even an attachment from database binary field too.

By apply code like above, you will able to return any file on button click without intervention of binary field.

I hope this answer will add extra spice into your knowledge and make your Odoo technical understanding more delicious.

Odoo Technical notes is published for this. You can view How to download any file on button click ?  and review it.

10
Avatar
Vazgeç
E.M.
Üretici

This is super detailed and extremely useful. I have pending to try in my project as we need it to generate custom printing files for a thermal printer. Thanks a lot.

Sarina

Does this code work for odoo10 as well . I got error while using these codes.

res = Model.read(model,cr, uid, [int(id)], fields, context)[0]

TypeError: unbound method read() must be called with kyc.clients instance as first argument (got unicode instance instead)

Avatar
Oleksandr Komarov
En İyi Yanıt

The easiest way to do this is using Transient model:

1. Create Transient Model with Binary field:

class GetFile(models.TransientModel):

_name = 'save.file.wizard'file_name = fields.Char('File name', readonly=True)

my_file = fields.Binary('File data', readonly=True,

help='File(jpg, csv, xls, exe, any binary or text format)')

2. Create Button on the Form in any Model(for example 'some_model'):

<button name="save_to_file" string="Save to file" type="object"

class="oe_stat_button oe_read_only" icon="fa-download"/>

3. Create function 'save_to_file' in model 'some_model':

@api.multi

def save_to_file(self):

some_data = 'This is data of file as String type'

my_file = self.env['save.file.wizard'].create({

'file_name': 'my-file.txt',

'xml_file': base64.b64encode(str.encode(xml_text)),

})

return {

'name': _('Download File'),

'res_id': my_file.id,

'res_model': 'o1c.save.conf',

'target': 'new',

'type': 'ir.actions.act_window',

'view_id': self.env.ref('my_module_name.save_file_wizand_view_done').id,

'view_mode': 'form',

'view_type': 'form',

}

4. Create Form for downloading files:

<record id="save_file_wizand_view_done" model="ir.ui.view">

<field name="name">save.file.wizard.form</field>

<field name="model">save.file.wizard</field>

<field name="arch" type="xml">

<form string="File download">

<group cols="2">

<div>

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

<label string="The file has been successfully generated." />

<field name="my_file" filename="file_name" nolabel="1" />

</div>

</group>

<footer>

<button special="cancel" string="Close" type="object" />

</footer>

</form>

</field>

</record>

That is all.

2
Avatar
Vazgeç
Avatar
Akhil P Sivan
En İyi Yanıt

Hi,

You may try using a Binary field.

file = fields.Binary(string='File')
2
Avatar
Vazgeç
Sehrish

Thanks it works in my case. I use binary field in some of my tasks, have a look: http://learnopenerp.blogspot.com/2016/06/using-binary-fields-in-odoo.html

Avatar
Bryan Sandoval
En İyi Yanıt

def get_input_template(self):

    url = str('/hr_horizontal_payroll/static/src/xls/template.xlsx')

    return {'type' : 'ir.actions.act_url','url': url,'target': 'self','tag': 'reload', }

0
Avatar
Vazgeç
Avatar
E.M.
Üretici En İyi Yanıt

This works fine but I do not fully understand this part of the code:

Model = request.registry[model]     
cr, uid, context = request.cr, request.uid, request.context     
fields = [field]
res = Model.read(cr, uid, [int(id)], fields, context)[0]

What does Model contain?

What does fields contain?

What does res contain?

0
Avatar
Vazgeç
David Yao

hey, I got the same problem, did you figure out how?

Avatar
chesucr
En İyi Yanıt
This works in Odoo 11 at least. If you have a binary field in any model:

@api.multi
def crete_and_download_dummy_field(self):

# store here your binary file into the dummy field

return {
'name': 'FEC',
'type': 'ir.actions.act_url',
'url': '/web/content/?model=sale.order&id={}&field=dummy&filename_field=dummy_filename&download=true'.format(
self.id
),
'target': 'self',
}

If you just want a link to download it in a form you can create a binary file and its name

mock_pdf = fields.Binary(string='Mock pdf')

mock_pdf_filename = fields.Char(
string='Mock PDF Filename',
compute='_compute_mock_pdf_filename'
)

@api.depends('mock_pdf')
def _compute_mock_pdf_filename(self):
self.ensure_one()
name = self.name.replace('/', '_')
name = name.replace('.', '_')
name = name + '.pdf'
self.mock_pdf_filename = name

And in the form

<field name="mock_pdf_filename" invisible="1" />
<field name="mock_pdf" filename="mock_pdf_filename" />
0
Avatar
Vazgeç
osama khalid

perfect ,worked for me in odoo13 as well,

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Üye Ol
İlgili Gönderiler Cevaplar Görünümler Aktivite
[8.0]How to confirm an element's state from: action_confirm (MRP_REPAIR)
python odooV8
Avatar
1
May 21
4984
How to get the file downloaded at the server?
python button file download controllers
Avatar
4
Haz 20
7306
How to save data in readonly field in openerp?
python odooV8
Avatar
Avatar
Avatar
Avatar
4
Eki 19
10898
How to multiply sequence by non-int Çözüldü
python odooV8
Avatar
Avatar
1
Oca 18
10329
Data in the txt file are all in one line
python line file download txt
Avatar
0
Eyl 17
4365
Topluluk
  • Eğitim Araçları
  • Dokümantasyon
  • Forum
Açık Kaynak
  • İndirin
  • Github
  • Runbot
  • Çeviriler
Hizmetler
  • Odoo.sh Hosting
  • Destek
  • Sürüm Yükseltme
  • Özel Geliştirmeler
  • Eğitim
  • Muhasebeci Bulun
  • Partner Bulun
  • Partner Olun
Hakkında
  • Şirketimiz
  • Pazarlama Gereçleri
  • İletişim
  • Kariyer
  • Etkinlikler
  • Podcast
  • Blog
  • Müşteriler
  • Hukuki • Gizlilik
  • Güvenlik
الْعَرَبيّة 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, müşteri ilişkileri yönetimi, eTicaret, muhasebe, envanter, satış noktası, proje yönetimi gibi şirketinizin tüm ihtiyaçlarını karşılayan bir açık kaynak işletme uygulamaları paketidir.

Odoo’nun eşsiz değer önermesi, aynı anda hem kullanımının çok kolay olup hem de tamamen entegre olmasıdır.

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