表單是給管理者新增書籍:
到views底下新增library_menu.xml 以下code就能輸入書的基本資料,用group分別列出要輸入的資料
<odoo>
<record id="view_form_book" model="ir.ui.view">
<field name="name">Book Form</field>
<field name="model">library.book</field>
<field name="arch" type="xml">
<form>
<header>
<button name="button_check_isbn" type="object"
string="Check ISBN" />
</header>
<sheet>
<group name="group_top">
<group name="group_left">
<field name="name" />
<field name="author_ids" widget="many2many_tags" />
<field name="publisher_id" />
<field name="date_published" />
</group>
<group name="group_right">
<field name="isbn" />
<field name="active" />
<field name="image" widget="image" />
</group>
</group>
</sheet>
</form>
</field>
</record>
</odoo>
新增書籍後,顯示的內容能自行定義,另外也能使用搜尋
到views/book_view.xml,以下code定義顯示的內容,包含書名、作者、出版社、出版日期:
<record id="view_tree_book" model="ir.ui.view">
<field name="name">Book List</field>
<field name="model">library.book</field>
<field name="arch" type="xml">
<tree>
<field name="name"/>
<field name="author_ids" widget="many2many_tags" />
<field name="publisher_id"/>
<field name="date_published"/>
</tree>
</field>
</record>
搜尋功能一樣在book_view.xml裡新增:
<record id="view_search_book" model="ir.ui.view">
<field name="name">Book Filters</field>
<field name="model">library.book</field>
<field name="arch" type="xml">
<search>
<field name="publisher_id"/>
<filter name="filter_inactive"
string="Inactive"
domain="[('active','=',True)]"/>
<filter name="filter_active"
string="Active"
domain="[('active','=',False)]"/>
</search>
</field>
</record>
Check ISBN 的按鈕,已經先做好了,會出現在新增書籍的上放,這邊就是要讓功能啟用。
到models/library_book.py裡,來確認ISBN是否有效:
def _check_isbn(self):
self.ensure_one()
digits = [int(x) for x in self.isbn if x.isdigit()]
if len(digits) == 13:
ponderations = [1, 3] * 6
terms = [a * b for a, b in zip(digits[:12], ponderations)]
remain = sum(terms) % 10
check = 10 - remain if remain != 0 else 0
return digits[-1] == check
def button_check_isbn(self):
for book in self:
if not book.isbn:
raise ValidationError("Please provide an ISBN for %s" % book.name)
if book.isbn and not book._check_isbn():
raise ValidationError("%s ISBN is invalid" % book.isbn)
return True
web測試我們來做一個書籍清單,讓使用者看到目前的書籍。
我們先到library_app/init.py裡新增,新增controllers目錄:
from . import controllers
ibrary_app/controllers/init.py裡新增,根據main來做調整:
from . import main
library_app/controllers/main.py:
from odoo import http
class Books(http.Controller):
@http.route("/library/books")
def list(self, **kwargs):
Book = http.request.env["library.book"]
books = Book.search([])
return http.request.render(
"library_app.book_list_template",
{"books": books}
)
在到views/book_list_template.xml
<odoo>
<template id="book_list_template" name="Book List">
<div id="wrap" class="container">
<h1>Books</h1>
<t t-foreach="books" t-as="book">
<div class="row">
<span t-field="book.name" />,
<span t-field="book.date_published" />,
<span t-field="book.publisher_id" />
</div>
</t>
</div>
</template>
</odoo>
最後進入http://my-server/library/books,這樣簡單的書本清單就有了。