Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: A Library Module

Build a complete Odoo library module on paper: manifest, models, security, views, menus, a report and demo data, with a runnable Python prototype of the business logic.

Time to put the chapters together. In this project you design a small but complete Odoo app, Library, that tracks books, members and loans. You will see every file a real module needs, in the right order, and you will prototype the business rules in Python so you can test them before they live inside Odoo.

Odoo cannot run on this site, so the module files are read-only. They are written for a current Odoo version (the <list> tag and expression-based invisible attributes), so check small differences if you use an older one. The Python prototype is runnable and mirrors the model methods.

Requirements

  • Keep a catalogue of books with title, ISBN, author and number of copies.
  • Register loans: who borrowed which book, when, and the due date.
  • A librarian can lend and return; members can only see their own loans.
  • Block lending when no copy is available; calculate overdue fees on return.
  • Print a loan slip and notify members about overdue loans every day.

The module layout

TEXT
library/
  __manifest__.py
  __init__.py
  models/
    __init__.py
    book.py
    loan.py
  security/
    library_security.xml
    ir.model.access.csv
  views/
    book_views.xml
    loan_views.xml
    menus.xml
  report/
    loan_report.xml
  data/
    cron.xml
  demo/
    demo.xml

The manifest

Python
{
    "name": "Library",
    "version": "1.0",
    "category": "Services/Library",
    "summary": "Books, members and loans",
    "depends": ["base", "mail"],
    "data": [
        "security/library_security.xml",
        "security/ir.model.access.csv",
        "views/book_views.xml",
        "views/loan_views.xml",
        "views/menus.xml",
        "report/loan_report.xml",
        "data/cron.xml",
    ],
    "demo": ["demo/demo.xml"],
    "application": True,
    "license": "LGPL-3",
}

The order of data follows one rule: things that others refer to come first. Security groups come before access rows, views before the menus that use their actions.

The models

Python
from datetime import timedelta
from odoo import api, fields, models
from odoo.exceptions import UserError, ValidationError


class LibraryBook(models.Model):
    _name = "library.book"
    _description = "Book"
    _order = "name"

    name = fields.Char(required=True)
    isbn = fields.Char(copy=False)
    author_id = fields.Many2one("res.partner", string="Author")
    copies = fields.Integer(default=1)
    loan_ids = fields.One2many("library.loan", "book_id")
    available_copies = fields.Integer(compute="_compute_available", store=True)

    _isbn_unique = models.Constraint("UNIQUE(isbn)", "The ISBN must be unique.")

    @api.depends("copies", "loan_ids.state")
    def _compute_available(self):
        for book in self:
            out = len(book.loan_ids.filtered(lambda l: l.state == "open"))
            book.available_copies = book.copies - out

(In Odoo 17 and earlier, the unique rule is written as _sql_constraints = [("isbn_unique", "unique(isbn)", "...")].)

Python
class LibraryLoan(models.Model):
    _name = "library.loan"
    _description = "Loan"
    _inherit = ["mail.thread"]

    book_id = fields.Many2one("library.book", required=True, ondelete="restrict")
    member_id = fields.Many2one("res.partner", required=True)
    date_out = fields.Date(default=fields.Date.today)
    date_due = fields.Date(compute="_compute_due", store=True, readonly=False)
    date_in = fields.Date()
    fee = fields.Float()
    state = fields.Selection([("open", "Open"), ("returned", "Returned")],
                             default="open", tracking=True)

    @api.depends("date_out")
    def _compute_due(self):
        for loan in self:
            loan.date_due = loan.date_out and loan.date_out + timedelta(days=14)

    @api.constrains("book_id", "state")
    def _check_available(self):
        for loan in self:
            if loan.state == "open" and loan.book_id.available_copies < 0:
                raise ValidationError("No copy of this book is available.")

    def action_return(self):
        for loan in self:
            if loan.state != "open":
                raise UserError("This loan is already closed.")
            today = fields.Date.today()
            late_days = max((today - loan.date_due).days, 0)
            loan.write({"state": "returned", "date_in": today, "fee": late_days * 0.25})

Security

The group file defines User (members read their own loans) and Librarian, and the CSV grants rights (Users and Groups, Access Rights with ir.model.access). A record rule keeps members to their own loans (Record Rules):

XML
<record id="rule_loan_member" model="ir.rule">
  <field name="name">Members see own loans</field>
  <field name="model_id" ref="model_library_loan"/>
  <field name="domain_force">[('member_id', '=', user.partner_id.id)]</field>
  <field name="groups" eval="[(4, ref('base.group_portal'))]"/>
</record>

Views, menus and report

The form has a header with a Return button (invisible="state != 'open'"), the list decorates overdue rows, and the search view offers "Open loans" and group by member (Form Views, Groups and Widgets, List, Search and Kanban Views). The report prints a slip (QWeb PDF Reports), and the cron sends overdue emails (Automated Actions, Cron Jobs and Email).

flowchart LR
    M["Member"] --> L["Loan (open)"]
    B["Book<br/>copies, available"] --> L
    L -->|"action_return"| R["Loan (returned)<br/>fee computed"]
    R --> B

Opening a loan uses one copy; returning it frees the copy and computes the late fee.

Prototype the logic in Python

Before wiring the module, test the rules in plain Python. This prototype mirrors available_copies, the availability check and action_return.

Python Prototype lending and returning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A nightly overdue job

The cron method needs the list of overdue loans and the message to send. This stand-in produces both, ready to be turned into send_mail calls.

Python Find overdue loans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Extension ideas

  1. Add a library.member model with a card number, or reuse res.partner with a flag.
  2. Add a kanban view of books grouped by availability.
  3. Expose /library/books as a public page (Controllers and HTTP Routes).
  4. Add an XML-RPC script that imports books from a CSV (External API: XML-RPC and JSON-RPC).
  5. Write tests with TransactionCase that mirror the prototype above.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does security/library_security.xml come before ir.model.access.csv in the manifest data list?

    Access rows name groups by external ID; the groups must exist when the CSV is loaded.
  2. 2. How is available_copies kept up to date?

    @api.depends makes Odoo recompute the stored value when copies or loan states change.
  3. 3. Which exception shows a friendly message for a rule broken by the user's action, such as returning twice?

    UserError and ValidationError are displayed to the user as dialogs without a traceback.
  4. 4. Which record rule would let portal members see only their own loans?

    The domain compares the loan's member with the current user's partner.

Summary

  • A module is a manifest plus models, security, views, menus, reports and data, loaded in dependency order.
  • Computed stored fields and constraints keep rules in the model, not in the views.
  • Groups, access rows and record rules protect librarians and members differently.
  • Prototyping the logic in plain code is a quick way to find rule mistakes.

Next: Project: A Helpdesk Workflow