Typeerror: view.getcontroller - python

Error:
Odoo Server Error
Traceback (most recent call last):
File "F:\odoo-14.0\odoo-14.0\odoo\tools\convert.py", line 677, in _tag_root
f(rec)
File "F:\odoo-14.0\odoo-14.0\odoo\tools\convert.py", line 655, in _tag_template
return self._tag_record(record)
File "F:\odoo-14.0\odoo-14.0\odoo\tools\convert.py", line 580, in _tag_record
record = model._load_records([data], self.mode == 'update')
File "F:\odoo-14.0\odoo-14.0\odoo\models.py", line 4213, in _load_records
records = self._load_records_create([data['values'] for data in to_create])
File "F:\odoo-14.0\odoo-14.0\odoo\models.py", line 4142, in _load_records_create
return self.create(values)
File "<decorator-gen-43>", line 2, in create
File "F:\odoo-14.0\odoo-14.0\odoo\api.py", line 345, in _model_create_multi
return create(self, arg)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 482, in create
return super(View, self).create(vals_list)
File "<decorator-gen-65>", line 2, in create
File "F:\odoo-14.0\odoo-14.0\odoo\api.py", line 345, in _model_create_multi
return create(self, arg)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_fields.py", line 534, in create
recs = super().create(vals_list)
File "<decorator-gen-13>", line 2, in create
File "F:\odoo-14.0\odoo-14.0\odoo\api.py", line 345, in _model_create_multi
return create(self, arg)
File "F:\odoo-14.0\odoo-14.0\odoo\models.py", line 3903, in create
fields[0].determine_inverse(batch_recs)
File "F:\odoo-14.0\odoo-14.0\odoo\fields.py", line 1185, in determine_inverse
getattr(records, self.inverse)()
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 300, in _inverse_arch
view.write(data)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 500, in write
res = super(View, self).write(self._compute_defaults(vals))
File "F:\odoo-14.0\odoo-14.0\odoo\models.py", line 3687, in write
real_recs._validate_fields(vals, inverse_fields)
File "F:\odoo-14.0\odoo-14.0\odoo\models.py", line 1266, in _validate_fields
check(self)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 411, in _check_xml
)).with_traceback(e.__traceback__) from None
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 385, in _check_xml
view_def = view.read_combined(['arch'])
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 809, in read_combined
arch = root.apply_view_inheritance(arch_tree, self.model)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 750, in apply_view_inheritance
return self._apply_view_inheritance(source, inherit_tree)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 758, in _apply_view_inheritance
source = view.apply_inheritance_specs(source, arch_tree)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 735, in apply_inheritance_specs
self.handle_view_error(str(e))
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_ui_view.py", line 673, in handle_view_error
raise ValueError(formatted_message).with_traceback(from_traceback) from from_exception
odoo.exceptions.ValidationError: Error while validating view:
Element '<xpath expr="//script[last()]">' cannot be located in parent view
View name: QUnit Assets
Error context:
view: ir.ui.view(1033,)
xmlid: qunit_suite
view.parent: ir.ui.view(199,)
file: f:\odoo-14.0\odoo-14.0\custom\muk_web_utils\template\assets.xml
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_http.py", line 237, in _dispatch
result = request.dispatch()
File "F:\odoo-14.0\odoo-14.0\odoo\http.py", line 684, in dispatch
result = self._call_function(**self.params)
File "F:\odoo-14.0\odoo-14.0\odoo\http.py", line 360, in _call_function
return checked_call(self.db, *args, **kwargs)
File "F:\odoo-14.0\odoo-14.0\odoo\service\model.py", line 94, in wrapper
return f(dbname, *args, **kwargs)
File "F:\odoo-14.0\odoo-14.0\odoo\http.py", line 348, in checked_call
result = self.endpoint(*a, **kw)
File "F:\odoo-14.0\odoo-14.0\odoo\http.py", line 913, in __call__
return self.method(*args, **kw)
File "F:\odoo-14.0\odoo-14.0\odoo\http.py", line 532, in response_wrap
response = f(*args, **kw)
File "f:\odoo-14.0\odoo-14.0\addons\web\controllers\main.py", line 1393, in call_button
action = self._call_kw(model, method, args, kwargs)
File "f:\odoo-14.0\odoo-14.0\addons\web\controllers\main.py", line 1381, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "F:\odoo-14.0\odoo-14.0\odoo\api.py", line 396, in call_kw
result = _call_kw_multi(method, model, args, kwargs)
File "F:\odoo-14.0\odoo-14.0\odoo\api.py", line 383, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "<decorator-gen-72>", line 2, in button_immediate_install
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_module.py", line 74, in check_and_log
return method(self, *args, **kwargs)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_module.py", line 475, in button_immediate_install
return self._button_immediate_function(type(self).button_install)
File "F:\odoo-14.0\odoo-14.0\odoo\addons\base\models\ir_module.py", line 593, in _button_immediate_function
modules.registry.Registry.new(self._cr.dbname, update_module=True)
File "F:\odoo-14.0\odoo-14.0\odoo\modules\registry.py", line 89, in new
odoo.modules.load_modules(registry._db, force_demo, status, update_module)
File "F:\odoo-14.0\odoo-14.0\odoo\modules\loading.py", line 460, in load_modules
loaded_modules, update_module, models_to_check)
File "F:\odoo-14.0\odoo-14.0\odoo\modules\loading.py", line 348, in load_marked_modules
perform_checks=perform_checks, models_to_check=models_to_check
File "F:\odoo-14.0\odoo-14.0\odoo\modules\loading.py", line 221, in load_module_graph
load_data(cr, idref, mode, kind='data', package=package)
File "F:\odoo-14.0\odoo-14.0\odoo\modules\loading.py", line 69, in load_data
tools.convert_file(cr, package.name, filename, idref, mode, noupdate, kind)
File "F:\odoo-14.0\odoo-14.0\odoo\tools\convert.py", line 733, in convert_file
convert_xml_import(cr, module, fp, idref, mode, noupdate)
File "F:\odoo-14.0\odoo-14.0\odoo\tools\convert.py", line 799, in convert_xml_import
obj.parse(doc.getroot())
File "F:\odoo-14.0\odoo-14.0\odoo\tools\convert.py", line 719, in parse
self._tag_root(de)
File "F:\odoo-14.0\odoo-14.0\odoo\tools\convert.py", line 685, in _tag_root
)) from e
Exception
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "F:\odoo-14.0\odoo-14.0\odoo\http.py", line 640, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "F:\odoo-14.0\odoo-14.0\odoo\http.py", line 316, in _handle_exception
raise exception.with_traceback(None) from new_cause
odoo.tools.convert.ParseError: while parsing None:73, near
<data name="QUnit Assets" inherit_id="web.qunit_suite">
<xpath expr="//script[last()]" position="after">
<script type="text/javascript" src="/muk_web_utils/static/tests/fields.js"/>
</xpath>
</data>
and here is my code:
/**********************************************************************************
*
* Copyright (c) 2017-2019 MuK IT GmbH.
*
* This file is part of MuK Web Utils
* (see https://mukit.at).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**********************************************************************************/
odoo.define('muk_web_utils.tests.fields', function (require) {
"use strict";
var basicFields = require('web.basic_fields');
var concurrency = require('web.concurrency');
var config = require('web.config');
var core = require('web.core');
var FormView = require('web.FormView');
var KanbanView = require('web.KanbanView');
var ListView = require('web.ListView');
var session = require('web.session');
var testUtils = require('web.test_utils');
var field_registry = require('web.field_registry');
var createView = testUtils.createView;
var createAsyncView = testUtils.createAsyncView;
var DebouncedField = basicFields.DebouncedField;
var JournalDashboardGraph = basicFields.JournalDashboardGraph;
var _t = core._t;
QUnit.module('muk_web_utils', {}, function () {
QUnit.module('fields', {
beforeEach: function () {
this.data = {
partner: {
fields: {
display_name: {
string: "Displayed name",
type: "char",
searchable: true
},
short: {
string: "Short",
type: "char",
searchable: true,
trim: true
},
long: {
String: "Long",
string: "txt",
type: "text",
},
document: {
string: "Binary",
type: "binary",
attachment: true,
},
},
records: [{
id: 1,
display_name: "first record",
short: "Short Text",
long: "Super looooooong Text",
document: 'coucou==\n',
}],
},
};
}
}, function () {
QUnit.module('BinaryFileCopy');
QUnit.test('Fields is correctly rendered', function (assert) {
assert.expect(2);
var form = createView({
View: FormView,
model: 'partner',
data: this.data,
arch: (
'<form string="Partners">' +
'<field name="document" widget="copy_binary" filename="short"/>' +
'<field name="short"/>' +
'</form>'
),
res_id: 1,
});
assert.strictEqual(
form.$('a.o_field_widget[name="document"] > .mk_copy_binary > .mk_copy_button').length,
1, "the copy button should be visible in readonly mode"
);
form.$buttons.find('.o_form_button_edit').click();
assert.strictEqual(
form.$('a.o_field_widget[name="document"] > .mk_copy_binary').length,
0, "the copy button shouldn't be visible in edit mode"
);
form.destroy();
});
QUnit.module('CharShare');
QUnit.test('Fields is correctly rendered', function (assert) {
assert.expect(1);
var form = createView({
View: FormView,
model: 'partner',
data: this.data,
arch: (
'<form string="Partners">' +
'<div>' +
'<field name="short" widget="share_char"/>' +
'</div>' +
'</form>'
),
res_id: 1,
});
assert.strictEqual(
form.$('span.o_field_widget[name="short"] > .mk_share_dropdown.mk_share_char').length,
1, "the copy button should be visible in readonly mode"
);
form.destroy();
});
QUnit.module('TextShare');
QUnit.test('Fields is correctly rendered', function (assert) {
assert.expect(1);
var form = createView({
View: FormView,
model: 'partner',
data: this.data,
arch: (
'<form string="Partners">' +
'<div>' +
'<field name="long" widget="share_text"/>' +
'</div>' +
'</form>'
),
res_id: 1,
});
assert.strictEqual(
form.$('span.o_field_widget[name="long"] > .mk_share_dropdown.mk_share_text').length,
1, "the copy button should be visible in readonly mode"
);
form.destroy();
});
QUnit.module('BinaryFileShare');
QUnit.test('Fields is correctly rendered', function (assert) {
assert.expect(2);
var form = createView({
View: FormView,
model: 'partner',
data: this.data,
arch: (
'<form string="Partners">' +
'<field name="document" widget="share_binary" filename="short"/>' +
'<field name="short"/>' +
'</form>'
),
res_id: 1,
});
assert.strictEqual(
form.$('a.o_field_widget[name="document"] > .mk_share_dropdown > .mk_share_button').length,
1, "the share dropdown should be visible in readonly mode"
);
form.$buttons.find('.o_form_button_edit').click();
assert.strictEqual(
form.$('a.o_field_widget[name="document"] > .mk_share_dropdown > .mk_share_button').length,
0, "the share dropdown shouldn't be visible in edit mode"
);
form.destroy();
});
});
});
});
When i upgrade this module from odoo 12 to odoo 14 then this error occured.When I changed the xpath and install this module its show an error typerror:view.getcontroller(....)then.guardedcatch is not a function. I have no idea about this error how can i fix it and in my code where i need to change please help me.

<xpath expr="//script[last()]" position="after">
Odoo can't able to get the above expr path so please check your inherited_id in v14.
or try to rewrite as this:
<template id="qunit_suite" name="QUnit Assets" inherit_id="web.qunit_suite">
<xpath expr="//script[last()]" position="after">
<script type="text/javascript" src="/muk_web_utils/static/tests/fields.js" />
</xpath>
</template>

Related

in _default raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")

These are my codes but i am not sure why the error is still appearing, and I try to convert from Cursor to json but nothing is happening
in the following code i need is to take input from form and return data from mongodb server so i can take these data and apply some filtering on it
filter.py
# import json
from ast import dump
from flask import Flask, jsonify, request, session, redirect
from app import db
import pymongo
from bson.json_util import dumps
import json
from bson import json_util
class Filter():
def __init__(self):
pass
def filter_tweets(self):
conditions = {
"filterby":request.form.getlist('checkbox'),
"forlikes":request.form.get('likeElements'),
"forreplies":request.form.get('replyElements'),
"forretweets":request.form.get('retweetElements'),
"likenumber":request.form.get('forlike'),
"likenumber":request.form.get('forreply'),
"likenumber":request.form.get('forretweets'),
}
session['conditions'] = conditions
session['data'] = db.tweets.find().sort(str(session['conditions']['filterby']),pymongo.ASCENDING)
json_docs = []
for doc in session['data']:
json_docs.append(doc)
return json_docs
her as you can see my routes in ('/myTweets') route to to apply the method to filter data after that it will return them filtered
routes.py
#app.route('/tweets/filter')
def filter():
return render_template('filtering.html')
#app.route('/myTweets',methods=['POST'])
def filter_tweet():
test = Filter().filter_tweets()
return test
#app.route('/test')
def test():
test = Filter().filter_tweets()
return render_template('test.html')
and this is my js code to take me to the next route after submetting
scripts.js
$("form[name=filter-form").submit(function (e) {
var $form = $(this);
var $error = $form.find(".error");
var data = $form.serialize();
$.ajax({
url: "/myTweets",
type: "POST",
data: data,
dataType: "json",
success: function (resp) {
window.location.href = "/test";
},
error: function (resp) {
$error.text(resp.responseJSON.error).removeClass("error--hidden");
}
})
e.preventDefault();
})
errors appering:
127.0.0.1 - - [25/Aug/2022 14:22:18] "POST /myTweets HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\app.py", line 1823, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\app.py", line 1844, in finalize_request
response = self.process_response(response)
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\app.py", line 2340, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\sessions.py", line 409, in save_session
val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\itsdangerous\serializer.py", line 207, in dumps
payload = want_bytes(self.dump_payload(obj))
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\itsdangerous\url_safe.py", line 53, in dump_payload
json = super().dump_payload(obj)
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\itsdangerous\serializer.py", line 169, in dump_payload
return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\json\tag.py", line 308, in dumps
return dumps(self.tag(value), separators=(",", ":"))
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\json\__init__.py", line 124, in dumps
return app.json.dumps(obj, **kwargs)
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\json\provider.py", line 230, in dumps
return json.dumps(obj, **kwargs)
File "C:\Users\hadim\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\hadim\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\hadim\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\hadim\Desktop\StageProject\Flask&MongoDB\env\lib\site-packages\flask\json\provider.py", line 122, in _default
raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
TypeError: Object of type Cursor is not JSON serializable
pl
.find() returns a cursor. If you want to output the data to json, convert it to a list first:
session['data'] = list(db.tweets.find().sort(str(session['conditions']['filterby']),pymongo.ASCENDING))

ValueError: Method eth_maxPriorityFeePerGas not supported, web3.py with ganache

I'm running the following code with web3.py:
transaction = SimpleStorage.constructor().buildTransaction(
{"chainId": chain_id, "from": my_address, "nonce": nonce}
)
And I am running into the following error:
Traceback (most recent call last):
File "/Users/patrick/code/web3_py_simple_storage/deploy.py", line 64, in <module>
transaction = SimpleStorage.constructor().buildTransaction(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/eth_utils/decorators.py", line 18, in _wrapper
return self.method(obj, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/contract.py", line 684, in buildTransaction
return fill_transaction_defaults(self.web3, built_transaction)
File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/_utils/transactions.py", line 121, in fill_transaction_defaults
default_val = default_getter(web3, transaction)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/_utils/transactions.py", line 71, in <lambda>
web3.eth.max_priority_fee + (2 * web3.eth.get_block('latest')['baseFeePerGas'])
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/eth.py", line 549, in max_priority_fee
return self._max_priority_fee()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/manager.py", line 198, in request_blocking
return self.formatted_response(response,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/web3/manager.py", line 171, in formatted_response
raise ValueError(response["error"])
ValueError: {'message': 'Method eth_maxPriorityFeePerGas not supported.', 'code': -32000, 'data': {'stack': 'Error: Method eth_maxPriorityFeePerGas not supported.\n at GethApiDouble.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/geth_api_double.js:70:16)\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\n at GethDefaults.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/gethdefaults.js:15:12)\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\n at SubscriptionSubprovider.FilterSubprovider.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/subproviders/filters.js:89:7)\n at SubscriptionSubprovider.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/subproviders/subscriptions.js:137:49)\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\n at DelayedBlockFilter.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/delayedblockfilter.js:31:3)\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\n at RequestFunnel.handleRequest (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/lib/subproviders/requestfunnel.js:32:12)\n at next (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:136:18)\n at Web3ProviderEngine._handleAsync (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:123:3)\n at Timeout._onTimeout (/Applications/Ganache.app/Contents/Resources/static/node/node_modules/ganache-core/node_modules/web3-provider-engine/index.js:107:12)\n at listOnTimeout (internal/timers.js:531:17)\n at processTimers (internal/timers.js:475:7)', 'name': 'Error'}}
How do I fix this?
This is an issue from a new edition of web3.py.
You need to add gasPrice to your transaction, like so:
transaction = SimpleStorage.constructor().buildTransaction(
{"chainId": chain_id, "gasPrice": w3.eth.gas_price, "from": my_address, "nonce": nonce}
)
This is due to EIP1559 changing, and web3.py updating for the change.

Python Web3 Ganache - Traceback error on BuildTransaction

I am going through the freeCodeCamp course on YouTube and have caught an error regarding when I run. As I am trying to build a transaction into Ganache. I see in Ganache logs that there is activity as well. First time posting, so let me know what other information should I provide!
The course: Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial
transaction = SimpleStorage.constructor().buildTransaction(
{"chainId": chain_id, "from": my_address, "nonce": nonce}
)
The error that the terminal returns:
Traceback (most recent call last):
File "C:\Users\Justin\demos\web3_py_simple_storage\deploy.py",
line 60, in <module>
transaction = SimpleStorage.constructor().buildTransaction(
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\eth_utils\decorators.py", line 18, in _wrapper
return self.method(obj, *args, **kwargs)
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\contract.py", line 684, in buildTransaction
return fill_transaction_defaults(self.web3, built_transaction)
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\_utils\transactions.py", line 121, in fill_transaction_defaults
default_val = default_getter(web3, transaction)
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\_utils\transactions.py", line 67, in <lambda>
'gas': lambda web3, tx: web3.eth.estimate_gas(tx),
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\eth.py", line 759, in estimate_gas
return self._estimate_gas(transaction, block_identifier)
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\manager.py", line 197, in request_blocking
response = self._make_request(method, params)
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\manager.py", line 150, in _make_request
return request_func(method, params)
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\middleware\formatting.py", line 76, in apply_formatters
response = make_request(method, params)
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\middleware\gas_price_strategy.py", line 90,
in middleware
return make_request(method, params)
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\middleware\formatting.py", line 74, in apply_formatters
response = make_request(method, formatted_params)
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\middleware\attrdict.py", line 33, in middleware
response = make_request(method, params)
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\middleware\formatting.py", line 74, in apply_formatters
response = make_request(method, formatted_params)
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\middleware\formatting.py", line 73, in apply_formatters
formatted_params = formatter(params)
File "cytoolz\functoolz.pyx", line 503, in cytoolz.functoolz.Compose.__call__
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\eth_utils\decorators.py", line 91, in wrapper
return ReturnType(result) # type: ignore
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\eth_utils\applicators.py", line 22, in apply_formatter_at_index
yield formatter(item)
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\eth_utils\functional.py", line 45, in inner
return callback(fn(*args, **kwargs))
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\eth_utils\applicators.py", line 84, in apply_formatters_to_dict
yield key, formatters[key](item)
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\eth_utils\applicators.py", line 72, in apply_formatter_if
return formatter(value)
File "cytoolz\functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
File "C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\web3\middleware\validation.py", line 57, in validate_chain_id
raise ValidationError(
web3.exceptions.ValidationError: The transaction declared chain ID 5777, but the connected node is on 1337
The Full Code that I used is below:
from solcx import compile_standard, install_solc
import json
from web3 import Web3
with open("./SimpleStorage.sol", "r") as file:
simple_storage_file = file.read()
# Compile Our Solidity
print("Installing...")
install_solc("0.6.0")
compiled_sol = compile_standard(
{
"language": "Solidity",
"sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
"settings": {
"outputSelection": {
"*": {
"*": [
"abi",
"metadata",
"evm.bytecode",
"evm.bytecode.sourceMap",
]
}
}
},
},
solc_version="0.6.0",
)
with open("compiled_code.json", "w") as file:
json.dump(compiled_sol, file)
# get bytecode
bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
"bytecode"
]["object"]
# get abi
abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]
# for connecting to ganache
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:7545"))
chain_id = 5777
my_address = "0xf2580f5ddfFb89e69A12a7CbCa8CA175Df4cBe08"
private_key = "0x937073896304af4297e6bbb3a3c623689d48388aa8595058752fafb522b31a13"
# Create the contract in python
SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
print(SimpleStorage)
# Get the latest transaction
nonce = w3.eth.getTransactionCount(my_address)
print(nonce)
# 1. Build a transaction
# 2. Sign a transaction
# 3. Send a transaction
transaction = SimpleStorage.constructor().buildTransaction(
{"chainId": chain_id, "from": my_address, "nonce": nonce}
)
print(transaction)
As of 5.25.0 of web3.py, we now need to add gasPrice to our transactions with a local Ganache chain. Adding "gasPrice": w3.eth.gas_price should fix your issue in the transactions.
Full Example:
transaction = SimpleStorage.constructor().buildTransaction(
{
"chainId": chain_id,
"gasPrice": w3.eth.gas_price,
"from": my_address,
"nonce": nonce,
}
)
Use the following line in .buildTransaction:
transaction = SimpleStorage.constructor().buildTransaction(
{'from': address, 'nonce':nonce, 'chainId':chain_id,'gas': 1728712,
'gasPrice': w3.toWei('21', 'gwei')})
And change the chain_id = 1337.
The transaction declared chain ID 5777, but the connected node is on 1337.
You have to change your chain_id:
chain_id = 5777❌
But use the one below
chain_id = 1337✔
I was having this exact same problem. Including "gasPrice": w3.eth.gas_price, solved it originally, but it came back.
After some tweaking, I found that casting chain_id (because I was getting that from .env as well) as an int solved my problems.
So the full code looked like this:
transaction = SimpleStorage.constructor().buildTransaction(
{
"chainId": int(chain_id),
"gasPrice": w3.eth.gas_price,
"from": my_address,
"nonce": nonce,
}
)

ValueError: Invalid field u'field' in leaf "<osv.ExtendedLeaf: (u'field', u'in', [59]) on object (ctx: )>" - Odoo v8

I have these methods:
#api.depends('order_lines', 'order_lines.isbn')
def _get_products(self):
isbn = self.env['product.product']
for prodtmpl in self.order_lines:
isbn |= prodtmpl.isbn
return isbn
#api.model
def _get_act_window_dict(self, name):
mod_obj = self.env['ir.model.data']
result = mod_obj.xmlid_to_object(name)
if not result:
result = {
'view_type': 'form',
'view_mode': 'tree,form',
'res_model': 'stock.quant',
'name': 'Stock On Hand',
'type': 'ir.actions.act_window',
}
else:
result = result[0].read()[0]
return result
#api.multi
def action_open_isbn(self):
isbn = self._get_products()
result = self._get_act_window_dict('stock.product_open_quants')
result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]"
result['context'] = "{'search_default_locationgroup': 1, 'search_default_internal_loc': 1}"
return result
On method get_act_window_dict it should return products on quants, like on Qty On Hand from product.template
But it throws me this:
Traceback (most recent call last):
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 944, in call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\stock\stock.py", line 331, in read_group
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\models.py", line 2082, in read_group
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\models.py", line 4498, in _where_calc
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\osv\expression.py", line 662, in __init__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\osv\expression.py", line 830, in parse
ValueError: Invalid field u'isbn' in leaf "<osv.ExtendedLeaf: (u'isbn', u'in', [59]) on stock_quant (ctx: )>"
I've tried doing this:
#api.model
def _get_act_window_dict(self, name):
mod_obj = self.env['ir.model.data']
result = mod_obj.xmlid_to_object(name)
if not result:
result = {
'view_type': 'form',
'view_mode': 'tree,form',
'res_model': 'stock.quant',
'name': 'Stock On Hand',
'isbn': 'product_id',
'type': 'ir.actions.act_window',
}
else:
result = result[0].read()[0]
return result
Adding isbn to the dict result as product_id but same result.
So, any ideas?
PS: This is isbn field on my class:
isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
Of course it doesn't exist as isbn on stock.quant but it's a Many2one to product so it should pass somehow.
This line:
result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]"
should be:
result['domain'] = "[('product_id','in',[" + ','.join(map(str, isbn.ids)) + "])]"
No field isbn in stock.quant. Since isbn is object product.product, I think it's just the same with product_id of stock.quant

Elastic Search - Failed to parse query

I am using python-elasticsearch client - elasticsearch.py and elastic search fails to parse query when I try to update a document using update_by_query method.
My update body is as follows:
{
'script': {
'inline': 'ctx._source.viewers += info',
'params': {
'info': {
'time': datetime.datetime(2017, 3, 7, 18, 8, 50),
'viewer': 'abc#xyz.com'
}
}
}
}
Elastic Search is called as follows::
update = es.update_by_query(index=index_el,
doc_type='1',
q='delivery_reference_id:' + str(cam_id) +'',
body=doc)
A sample value for cam_id is:
CAM_10_DATA_4_2017-03-07 18:02:07
Internally, the following query is formed::
http://127.0.0.1:9200/user_tracker/1/_update_by_query?q=delivery_reference_id%3ACAM_10_DATA_4_2017-03-07+18%3A02%3A07
The error received is as follows:
TransportError(400, 'search_phase_execution_exception', 'Failed to parse query [delivery_reference_id:CAM_10_DATA_4_2017-03-07 18:02:07]')
The full error log is as follows:
Traceback (most recent call last):
File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\exception.py", line 42, in inner
response = get_response(request)
File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\rest_framework\views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "C:\Python34\lib\site-packages\rest_framework\views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Python34\lib\site-packages\rest_framework\views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\catch\PycharmProjects\myproject\myproj\apis\views.py", line 516, in get
viewer=viewer_email)
File "C:\Users\catch\PycharmProjects\myproject\myproj\apis\views.py", line 541, in update_track_info
doc=doc)
File "C:\Users\catch\PycharmProjects\myproject\myproj\apis\views.py", line 553, in es_update
body=doc)
File "C:\Python34\lib\site-packages\elasticsearch\client\utils.py", line 73, in _wrapped
return func(*args, params=params, **kwargs)
File "C:\Python34\lib\site-packages\elasticsearch\client\__init__.py", line 680, in update_by_query
doc_type, '_update_by_query'), params=params, body=body)
File "C:\Python34\lib\site-packages\elasticsearch\transport.py", line 318, in perform_request
status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
File "C:\Python34\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 128, in perform_request
self._raise_error(response.status, raw_data)
File "C:\Python34\lib\site-packages\elasticsearch\connection\base.py", line 122, in _raise_error
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'search_phase_execution_exception', 'Failed to parse query [delivery_reference_id:CAM_10_DATA_4_2017-03-07 18:02:07]')
Would be nice if someone figured it out. Let me know if more info is needed.
Appreciate it. Thanks in advance.
I think your query syntax is not up to date. I had good results with the following syntax:
{
"query": {
"bool": {
"must": [
{ "match": { "MYFIELD": "myoldvalue" } }
]
}
},
"script": {
"inline": "ctx._source.MYFIELD = \"mynewvalue\"",
"lang": "painless"
}
}
HTH :)

Categories

Resources