I have the following model:
class LibraryBook(models.Model):
_name = 'library.book'
name = fields.Char('Title', required=True)
date_release = fields.Date("Release Date")
author_ids = fields.Many2many("res.partner", string="Authors")
I'm new to Odoo and trying to understand the basics of how to save data to my model from a POST request like the following
curl -i -X POST --data "name=Odoo%20-%20Much%20Mystery,%20Wow&author_id=Doge" http://0.0.0.0:8069/test
I found a way doing this by setting the csrf
parameter in my controller to false
like so:
[...]
@http.route('/test', type='http', auth='public',methods=['POST'], website=True, csrf=False)
def test(self, **kwargs):
record = request.env['library.book'].sudo()
record.create(kwargs)
I'm wondering now if there is a way to avoid setting csrf=false
since I've read that it's a bad idea to do so in general. Also, what would I need to get rid of that .sudo()
? Not setting csrf=false
leads to a 400 BAD REQUEST
with Invalid CSRF token
. Removing sudo()
leads to a 500 INTERNAL SERVER ERROR
. In Odoo Development Cookbook it says in one example with auth='none'
Lack of a user is also why we have to sudo() all our calls to model methods in the example code
Assuming I would expect a POST request from an API, is it possible to associate it with a user so I don't have to sudo()
?
I would very much appreciate any clarification on this.
UPDATE
So I just found this (line 817):
- if the form is accessed by an external third party (e.g. REST API endpoint, payment gateway callback) you will need to disable CSRF
protection (and implement your own protection if necessary) by
passing thecsrf=False
parameter to theroute
decorator.
which I guess leaves only one question open, regarding sudo
.