Add an attachement (file) from odoo website. - BOOKC -->

Add an attachement (file) from odoo website.

Tuesday, January 1, 2019

In this article I am going to teach you how to add or upload attachment or file (doc, excel, zip, jpg, png etc) from odoo website or web page.


Add an attachement (file) from odoo website.

To upload files through web page you have to create a template and odoo controller.

Xml code:


<template id="detail" name="Project Detail">
 <t t-call="website.layout">
  <div class="col-md-offset-5 col-sm-offset-4 col-sm-8 col-md-7" style="margin-top:30px;">
   <form action="/project/uploaded" method="post" class="s_website_form form-horizontal container-fluid mt32" enctype="multipart/form-data" id="file_upload_form">
    <div t-attf-class="form-group">
     <div class="col-md-7 col-sm-8">
      <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
      <input type="hidden" name="project_id" t-att-value="project.id"/>
      <input type="file" name="attachment" class="file" multiple="true" data-show-upload="true" data-show-caption="true" lass="file" data-show-preview="true" id="project.id"/>
      <button type="submit" name="Upload" style="margin-top:20px;" class="fa fa-upload">
       Upload
      </button>
     </div>
    </div>
   </form>
  </div>
 </t>
</template>      
 

.py code:


@http.route('/project/uploaded', type='http', auth="public", website=True)
    def upload_files(self, **post):
        values = {}
        if post.get('attachment',False):
            Attachments = request.env['ir.attachment']
            name = post.get('attachment').filename      
            file = post.get('attachment')
            project_id = post.get('project_id')
            attachment = file.read() 
            attachment_id = Attachments.sudo().create({
                'name':name,
                'datas_fname': name,
                'res_name': name,
                'type': 'binary',   
                'res_model': 'model.model,
                'res_id': project_id,
                'datas': attachment.encode('base64'),
            })
            value = {
                'attachment' : attachment_id
            }
            return request.render("modulename.template_to_render", value)       
 

Code Description:

In above code snippet we have created an odoo template, and in that template we have created a HTML form tag, and set the action of that form as our odoo controller route. We have also take three input type fields and a submit button. When user clicks on submit button the form action goes to our odoo controller and save the attachement file in "ir.attachment" model.