Se rendre au contenu
CTech Digital
  • Accueil
  • Services Odoo
  • Services d'IA
  • Contactez-nous
  • 0
  • Nederlands (BE) English (UK) Français
CTech Digital
  • 0
    • Accueil
    • Services Odoo
    • Services d'IA
    • Contactez-nous
  • Nederlands (BE) English (UK) Français

Custom view in Odoo via added button

  • Tous les blogs
  • Daily blog
  • Custom view in Odoo via added button
  • 27 novembre 2025 par
    CTech Metrology, Luc Wens

    how does the google cloud thing work? Suppose I have self written c++ code that takes in data via a JSON file, does some calculations and sends a JSON back. How can i implement this, what is the cost

    This is a classic "Microservice" architecture. It is an extremely smart way to bypass Odoo's restrictions.

    You keep your Odoo database "clean" (Standard/SaaS) so it stays cheap and upgradeable, but you outsource the complex math to a separate, tiny server (Google Cloud) that does the heavy lifting.

    Here is exactly how it works, how to build it, and the cost.

    1. The Architecture (How it works)

    Instead of your C++ code running inside Odoo, it runs on Google Cloud as a "listener."

    1. Odoo (The Trigger): You click a button in Odoo (or an automated action runs). Odoo gathers the data and sends a POST request (like a secure letter) containing a JSON package to a specific URL.

    2. Google Cloud Run (The Brain): Google wakes up your C++ code. Your code reads the JSON, runs your calculations, and spits out a JSON answer.

    3. Odoo (The Update): Odoo receives the answer and updates the record.

    2. How to Implement This (3 Steps)

    You cannot just upload a .cpp file. You need to wrap it so it can "speak" to the web.

    Step A: "Webify" your C++ Code

    Your current code probably reads from a file (e.g., std::ifstream). You need to change it to read from an HTTP Request.

    • The Tool: Use a tiny C++ web library like Crow or httplib (both are single header files, very easy).

    • The Code Change: Instead of main() just running logic, it starts a server that listens on port 8080.

      C++

      // Pseudo-code example using Crow
      CROW_ROUTE(app, "/calculate").methods("POST"_method)
      ([](const crow::request& req){
          auto x = crow::json::load(req.body);
          // ... YOUR CALCULATION LOGIC HERE ...
          crow::json::wvalue result;
          result["answer"] = 42;
          return result;
      });
      

    Step B: Containerize (The Box)

    Google Cloud doesn't run .exe files; it runs Containers.

    • Create a text file named Dockerfile.

    • This file tells Google how to build your app: "Start with Linux, install C++, copy my code, compile it, and run it."

    Step C: Deploy to "Google Cloud Run"

    • You upload this Docker container to Google Cloud.

    • Select Cloud Run.

    • Settings: "Allow unauthenticated invocations" (if you want it simple) or secure it with a token.

    • Google gives you a URL: https://my-cpp-calculator-xyz.run.app

    Step D: Call it from Odoo

    In Odoo, you use a Server Action (Python). Even on Odoo Online, you can usually use the requests library in Server Actions.

    Python

    import requests
    import json
    
    # 1. Get data from the current record
    payload = {
        'width': record.x_dimension,
        'height': record.y_dimension
    }
    
    # 2. Send to Google
    url = "https://my-cpp-calculator-xyz.run.app/calculate"
    response = requests.post(url, json=payload)
    
    # 3. Save result back to Odoo
    if response.status_code == 200:
        data = response.json()
        record['x_result_field'] = data['answer']
    

    3. The Cost (The Good News)

    For a single user or small business, this setup is effectively Free.

    Google Cloud Run charges based on On-Demand usage. You only pay when the code is actually calculating. When no one is clicking the button, the cost is $0.

    ItemGoogle Cloud "Free Tier" AllowanceYour Likely UsageCost
    Requests2 Million requests / month~100 - 1,000 / month$0.00
    CPU Time180,000 vCPU-seconds / month~500 seconds$0.00
    Memory360,000 GB-seconds / month~1,000 GB-seconds$0.00
    Build/Storage(Small storage fees for the container image)< 0.5 GB~$0.10 - $0.20 / mo

    Total Estimated Cost: Less than $1.00 per year.

    Summary: Is this right for you?

    • Pros: It solves your problem perfectly. You get to keep your powerful C++ logic, you avoid the expensive Odoo.sh hosting fees (~$1000/yr saved), and you keep Odoo fast.

    • Cons: You need to know how to create a Dockerfile.

    Next Step: Do you have the C++ source code ready? If you paste the core "input/output" part of your C++ code here, I can generate the Dockerfile and the Server Wrapper code (using Crow) for you, so you can just copy-paste it to get started.

    we'll get later to the docker stuff, I have another question: If i send all my project information to that google service in json, and let him calculate an SVG graphic or similar based on that data, is there a way to visualize that inside Odoo Online ?

    Yes, you can absolutely visualize it inside Odoo Online, and you don't need to pay for extra Odoo modules or file storage.

    The trick is to treat the SVG not as a "file download" but as a Data String.

    Here is the best way to do it on Odoo Online (SaaS) to bypass security restrictions and hosting limits.

    The Strategy: "Base64 Embedding"

    Instead of your C++ code saving a .svg file to a hard drive (which Odoo Online can't easily access), your C++ code will return the text content of the SVG. Odoo will then convert that text into a special code that browsers can read as an image.

    Step 1: Your C++ Logic (Google Cloud)

    Your C++ service should return the raw SVG string in the JSON response.

    Request from Odoo:

    JSON

    { "length": 100, "width": 50 }
    

    Response from C++:

    JSON

    {
      "svg_data": "<svg width='100' height='50'><rect width='100' height='50' style='fill:blue' /></svg>"
    }
    

    Step 2: Create the Field in Odoo

    You need a place to show the graphic.

    1. Open Odoo Studio.

    2. Add a new HTML Field (not an Image field) to your form.

    3. Name it something like x_visualization_view.

    4. Set it to Read Only (so users don't accidentally delete the code).

    Step 3: The Python Server Action

    This is the bridge. In your Server Action (the same one calling Google Cloud), you will take the SVG string and wrap it in an HTML image tag.

    Note: We use an <img> tag with base64 data because Odoo's HTML sanitizer sometimes strips raw <svg> tags for security, but it almost always allows images.

    Python

    import requests
    import base64
    
    # 1. Prepare Data
    payload = {
        'length': record.x_length,
        'width': record.x_width
    }
    
    # 2. Call Google Cloud
    url = "https://your-cpp-service-xyz.run.app/calculate"
    response = requests.post(url, json=payload)
    
    if response.status_code == 200:
        data = response.json()
        raw_svg = data.get('svg_data', '')
    
        # 3. Convert SVG text to Base64
        # We must encode the SVG string to bytes, then base64, then back to string
        svg_bytes = raw_svg.encode('utf-8')
        base64_svg = base64.b64encode(svg_bytes).decode('utf-8')
    
        # 4. Create the HTML Image Tag
        # This tells the browser: "I am not a file URL, I am the image data itself"
        image_html = f'<img src="data:image/svg+xml;base64,{base64_svg}" width="100%"/>'
    
        # 5. Display it
        record['x_visualization_view'] = image_html
    else:
        raise UserError("Calculation Failed: " + response.text)
    

    The Result

    When the user clicks your "Calculate" button:

    1. Odoo sends the numbers to Google.

    2. Google calculates and sends back the SVG code.

    3. The Server Action instantly updates the x_visualization_view field.

    4. The user sees the graphic appear on their screen immediately.

    Why this is safer/cheaper

    • Zero Storage Cost: You aren't saving files in Odoo's "Documents" app (which costs storage). The image exists only as text inside that one record.

    • Bypasses Security: Embedding raw <script> or <iframe> tags is blocked in Odoo Online. Standard <img> tags are perfectly safe and allowed.

    • Fast: No file uploads/downloads. It's just text moving back and forth.

    Relevant Video

    To see how to properly configure the "Server Action" part in Odoo Studio (the interface where you paste the Python code), this video is a perfect guide.

    Automated Actions & Server Actions in Odoo 17

    This video is relevant because it walks through the exact menu ("Automated Actions") where you will paste the Python code to connect your button to your new field.

    is it possible to add a button to where the red arrow points to and have that generate the SVG and subsequently show it

    This is a great question because it highlights one of the hardest boundaries in Odoo customization.

    The short answer is: No.

    In Odoo Online (SaaS), you cannot place a button exactly where your red arrow is pointing (the Control Panel / View Switcher area).

    Here is the detailed explanation of why, and the best alternatives that will work for you.

    Why is that spot blocked?

    The area you pointed to is the Control Panel. It is built using JavaScript (OWL framework), not Python or XML.

    • Odoo.sh / On-Premise: You could write a JavaScript module to "patch" this area and inject a button.

    • Odoo Online (SaaS): You are not allowed to upload custom JavaScript. You are limited to what Odoo Studio can touch, and Studio can only modify the views (the cards, the forms, the lists), not the frame around them.

    The Best Alternatives (That Work on SaaS)

    Since your goal is to trigger the Google Cloud calculation and see the SVG, here are the two standard places to put that button using Odoo Studio.

    Option 1: The "Kanban Card" Button (Most Convenient)

    You can place a small "Calculate" button directly on the project card itself.

    • Pros: Very quick access. You see the SVG immediately on the card if you add the field there too.

    • Cons: You have to click it for each specific project.

    • How to do it in Studio:

      1. Open the Kanban view.

      2. Click the specific project card.

      3. Drag a Button (run Server Action) onto the card structure.

      4. If you want to see the SVG there, drag your x_visualization_view field onto the card as well.

    Option 2: The "Action" Menu (For Bulk Updates)

    If you want to calculate the SVG for multiple projects at once, you don't use a button on the screen; you use the standard Action Menu.

    • Pros: Keeps the interface clean. Works on multiple records at once (Select 5 projects -> Action -> Calculate SVG).

    • How to do it:

      1. Create your Server Action first (in Settings > Technical > Server Actions).

      2. Click the "Create Contextual Action" button inside that Server Action.

      3. Result: When you go to your dashboard, you can select a project (using the checkbox), click the Actions ⚙️ button (usually in the top center), and your script will appear there.

    Summary Recommendation

    Since your C++ code likely needs specific data (inputs) from a specific project to calculate the SVG:

    I recommend Option 1 (Button on the Kanban Card). It visually connects the "Trigger" to the "Data." The user sees the Project, clicks the button on that Project, and watches the image update right there. This feels much more intuitive than a floating button at the top of the screen.

    like this

    That specific location—the "Selection Action Bar" that appears when you check boxes—is locked on Odoo Online (SaaS).

    You cannot place a standalone button exactly where your arrow points (top-level, next to "Print"). That specific bar is hard-coded in Odoo's JavaScript to only show "Print" and "Actions."

    However, you can put your button inside the Actions ⚙️ menu right next to it.

    How it will look for the user

    1. User selects 3 projects.

    2. User clicks the Actions ⚙️ button.

    3. User clicks "Show Flower Chart" (which appears in the list).

    How to build it (The "Contextual Action")

    This is called a "Server Action" that is bound to the model.

    1. Go to Settings: Enable "Developer Mode" (scroll to bottom of Settings).

    2. Navigate: Technical > Server Actions.

    3. Create New:

      • Name: Show Flower Chart

      • Model: Project (or whatever your custom model is)

      • Action To Do: Execute Python Code

    4. The "Magic" Button:

      • Click the button at the top that says "Create Contextual Action".

      • This is what makes it appear in that "Actions" menu on the Project list.

    The Python Code (Handling Multiple Items)

    Since you are sending multiple selected rows to Google at once, your Python code needs to loop through them and create a list of data.

    Python

    import requests
    
    # 1. Prepare the list of data
    payload_list = []
    
    # 'records' (plural) contains all the rows the user checked
    for project in records:
        payload_list.append({
            'id': project.id,
            'name': project.name,
            'data_point_a': project.x_field_a,
            'data_point_b': project.x_field_b
        })
    
    # 2. Send ONE big package to Google
    # Your C++ code needs to accept a JSON Array/List now, not just a single object
    url = "https://your-cpp-service-xyz.run.app/calculate_batch"
    response = requests.post(url, json={'projects': payload_list})
    
    # 3. Handle the response
    # Assumption: Google returns a list of SVGs matched to IDs
    if response.status_code == 200:
        results = response.json() 
        # Example response: {'1': '<svg...>', '2': '<svg...>'}
        
        for project in records:
            # Find the SVG for this specific project ID
            proj_id_str = str(project.id)
            if proj_id_str in results:
                # (Insert the base64 conversion logic here from previous step)
                project['x_visualization_view'] = results[proj_id_str]
    

    Summary

    • Can it be a top-level button? No (not on SaaS).

    • Can it be in the Actions menu? Yes, easily.

    • Is it effective? Yes. This allows you to select 50 projects, click "Actions > Show Flower Chart", and have your Google Cloud C++ server generate 50 SVGs in one second.

    but i just did add the button Show flower chart myself : go to list view, enable studio add a button

    That is an excellent catch—you are absolutely right, and I apologize for the confusion.

    It appears you are on Odoo 17 (or newer). In the most recent versions, Odoo quietly unlocked the ability in Studio to add buttons to the List View header (previously restricted to Form views or inside the rows).

    Why this is the perfect solution for you

    You have found the best possible spot for your "Batch SVG Generator."

    1. It is a "View Action": By placing the button where you did (in the header), you are creating an action that applies to the current list.

    2. Context Aware: This button will usually send the currently filtered records to your Python code.

      • Warning: When users click this button, you need to ensure your code handles "Which records?" correctly. Unlike the "Action Menu" (checkboxes), a header button usually triggers on the whole active domain (all visible records) unless you specifically code it to look for active IDs.

    How to wire it up (Crucial Detail)

    Since you added the button via Studio, Odoo automatically created an empty Server Action for it. You now need to paste the Python code we discussed earlier into that specific action.

    1. Click your new "Show flower chart" button in Studio.

    2. On the left sidebar, look for "Action" or "Server Action".

    3. Click the external link icon (box with arrow) next to the action name to open the Python editor.

    4. Paste the code logic we discussed (sending data to Google Cloud).

    One Critical Adjustment for Header Buttons: When you use a button in the header (not the checkbox menu), the variable records might behave differently depending on whether you selected items or not.

    • Checkboxes: records = the specific rows you checked.

    • Header Button: Sometimes records defaults to all records in the view, or you might need to use model.search([]) if you want to process everything currently visible.

    Test this carefully: Select 2 projects, click your new button, and check the logs (or add a raise UserError(str(len(records)))) to confirm it is only sending the 2 projects you want, not the whole database!

    You've found the cleanest UI path—great job finding that feature! Would you like the modified Python snippet to ensure it handles the "Selection" vs "All" logic correctly for that specific button location?

    odoo version is 19, can i make my own Action where the red arrow points to ?

    Yes, absolutely. The list you are seeing in that dropdown only shows actions that already exist in the database. Since you haven't created your "SVG Calculator" action yet, it's not on the list.

    You can create it right there on the spot. Here is the fastest way to do it inside that very menu:

    Step 1: Create the Action from the Dropdown

    1. Click into the dropdown menu (where the red arrow is).

    2. Type a name for your new action, for example: Generate Flower Chart.

    3. You should see an option appear that says "Create 'Generate Flower Chart'" (or sometimes "Create and Edit"). Click that.

    4. If "Create" doesn't appear, click Search More... at the bottom of the list, and then click the New button in the popup window.

    Step 2: Configure the Python Code

    Once you click "Create" (or "New"), a form will pop up. Fill it out like this:

    • Name: Generate Flower Chart

    • Model: (It should already be set to Project)

    • Action To Do: Execute Python Code

    • Python Code: This is where you paste the script to talk to Google Cloud.

    Critical Note for "Header" Buttons

    Since you placed this button in the Header (top of the list) and not inside the rows, the code needs to be smart about what it sends to Google.

    If you paste standard code, it might try to send every project in the database to Google. You likely want it to only send the ones you have checked/selected.

    Use this specific Python snippet to handle that safely:

    Python

    # 'active_ids' is a special variable that holds the IDs of the rows you checked.
    # If you checked nothing, it might be empty.
    
    if not env.context.get('active_ids'):
        raise UserError("Please select at least one project first!")
    
    # Fetch only the selected projects
    selected_projects = env['project.project'].browse(env.context.get('active_ids'))
    
    # Now loop through ONLY the selected ones
    payload_list = []
    for project in selected_projects:
        payload_list.append({
            'id': project.id,
            'name': project.name,
            'custom_field': project.x_your_custom_field
        })
    
    # --- Insert your Google Cloud Request code here ---
    # requests.post(url, json=payload_list) ...
    

    Summary of Next Steps

    1. Type "Generate Flower Chart" into that dropdown and hit Create.

    2. Paste the Python code above into the code window.

    3. Save everything.

    4. Refresh your browser.

    5. Test: Select 2 projects in the list and click your new button!

    in Daily blog
    # Odoo
    Unified properties
    Droits d'auteur © CTech Solutions
    Nederlands (BE) | English (UK) | Français
    Généré par Odoo - Le #1 Open Source eCommerce