I' am trying to assign values when a users belongs into a project in this case the project name and manager to which he is assigned but the compute method gives an error, I've tried to log in the values just in case one of them came empty but no they definitely have the required data.
we can see in the logs:
root: Staff Augmentation - project_task.project_id.display_name
root: 120 - project_task.project_id.delivery_director.id
#api.depends('user_id')
#api.model
def _get_assigned_project(self):
today = fields.Date.today()
for employee in self:
project_task = self.env['project.task'].search([('user_id','=',employee.user_id.id),
('status','=','assigned'),
('date_end','>',today),
('project_id.original_project_id', '=', False)], order='date_end desc', limit=1)
if project_task:
employee.project_name = project_task.project_id.display_name
if project_task.project_id.role_id.name = 'Delivery Manager' and employee.base_manager != 0:
employee.parent_id = project_task.project_id.delivery_director.id
else:
employee.parent_id = project_task.project_id.delivery_manager.id
else:
employee.project_name = ""
if employee.base_manager != 0:
employee.parent_id = employee.base_manager
this is the error:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/odoo/src/odoo/odoo/http.py", line 640, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/odoo/src/odoo/odoo/http.py", line 316, in _handle_exception
raise exception.with_traceback(None) from new_cause
ValueError: Compute method failed to assign hr.employee(266,).project_name
You need to assign employee.parent_id in your compute method , If your if else are failed to assign the value to the field than this error will comes up.
So check your method and put an else condition after your if condition and give assignment like employee.parent_id = False.
Because if in any case your compute method failed to assign value which we think it should be, than they throws error.
Put default value for the field to be assigned in case it did'n fulfill the computed assignment condition
Related
I coded a field(a) on classA which is to automatically take the contents of another field(b) in another classB
After updating my own developing on a module I tried to fill in a form on tryton, then I tried to save the form.
But there was an error
Traceback (most recent call last):
File "/trytond/wsgi.py", line 104, in dispatch_request
return endpoint(request, **request.view_args)
File "/trytond/protocols/dispatcher.py", line 48, in rpc
request, database_name, *request.rpc_params)
File "/trytond/wsgi.py", line 72, in auth_required
return wrapped(*args, **kwargs)
File "/trytond/protocols/wrappers.py", line 131, in wrapper
return func(request, pool, *args, **kwargs)
File "/trytond/protocols/dispatcher.py", line 197, in _dispatch
result = rpc.result(meth(*c_args, **c_kwargs))
File "/trytond/model/modelsql.py", line 832, in read
getter_results = field.get(ids, cls, field_list, values=result)
File "/trytond/model/fields/function.py", line 106, in get
return dict((name, call(name)) for name in names)
File "/trytond/model/fields/function.py", line 106, in <genexpr>
return dict((name, call(name)) for name in names)
File "/trytond/model/fields/function.py", line 101, in call
return dict((r.id, method(r, name)) for r in records)
File "/trytond/model/fields/function.py", line 101, in <genexpr>
return dict((r.id, method(r, name)) for r in records)
File "/trytond/modules/module_designing/design.py", line 15702, in On_change_design
('Description', '=', self.id),
ValueError: not enough values to unpack (expected 1, got 0)
, the method mentioned on the error is this : (this method I used it on my field(b) on a class B to call another field(a) on another class A)
def On_change_design(self,Name):
Design = Pool().get('design.classA')
design, = Design.search([
('classB', '=', self.id),
])
return design.id
field(b) = fields.Function(fields.Many2One('design.classA', 'test'), 'On_change_design')
the field(b) which will take the contain of the field(a)
this is how I was coded the field(a):
field(a) = fields.Function(fields.Char('area '),'on_change_parameters')
Any help will be appreciated, I want to know what's wrong and what I should do.
Or can anyone help me and tell how I can code the method onchange to make the field(b) take automatically the contents of another field(a) from another class(a)
Function fields are computed after you save. On your function you are performing a search into a related table and unpacking the result. This has no problem when the search returns a single record but in your case the search does not return any record so this makes the code crash.
You should use a safer code, that tests if the serach return any result before unpacking. Something like this:
def on_change_design(self,Name):
Design = Pool().get('design.classA')
designs = Design.search([
('classB', '=', self.id),
], limit=1)
if designs:
design, = designs
return design.id
return None
Note that I also added a limit on the search to ensure a maximum of one record is returned. This will also prevent to crash when multiple records are returned but you may want a diferent behaviour. I also added a explicit None return to make it clar that function will return None when no search is found.
Problem:
I'm parsing some config file and one field should be parsed to an Enum. Let's say there may be 3 possible values:
`foo`, `bar`, `baz`
And I want to parse them into the following enum's values:
class ConfigField(Enum):
FOO = 'foo'
BAR = 'bar'
BAZ = 'baz'
What have I tried so far:
I have written the following function to do that:
def parse_config_field(x: str) -> ConfigField:
for key, val in ConfigField.__members__.items():
if x == val.value:
return val
else:
raise ValueError('invalid ConfigField: ' + str(x))
But I think this is ugly and too complicated for something so simple and straightforward.
I also considered just lowercasing enum field's names:
def parse_config_field2(x: str) -> ConfigField:
value = ConfigField.__members__.get(x.lower(), None)
if value is None:
raise ValueError('invalid ConfigField: ' + str(x))
else:
return value
Which is slightly shorter, but still pretty ugly and what's worse, it creates direct dependence between config values (in some text config file) and ConfigField which I'm not comfortable with.
I just recently switched from python2 to python3 so I'm not 100% familiar with Enums and I'm hoping there may be a better way to do this.
Question:
Is there a better way to do this? I'm looking for simpler (and perhaps more "built-in" / "pythonic") solution than my parse_config_field - perhaps something like:
value = ConfigField.get_by_value(cfg_string)
I believe you are looking for accessing by value: ConfigField("foo"), which gives <ConfigField.FOO: 'foo'>.
A ValueError will be raised for parsing using not existing values:
>>> ConfigField("not foo")
ValueError: 'not foo' is not a valid ConfigField
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Program Files\Python38\lib\enum.py", line 309, in __call__
return cls.__new__(cls, value)
File "C:\Program Files\Python38\lib\enum.py", line 600, in __new__
raise exc
File "C:\Program Files\Python38\lib\enum.py", line 584, in __new__
result = cls._missing_(value)
File "C:\Program Files\Python38\lib\enum.py", line 613, in _missing_
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 'not foo' is not a valid ConfigField
I am trying to run this command python run.py --mode MLE
and got this error. I am not able to find the correct solution for it .
Traceback (most recent call last):
File "run.py", line 208, in <module>
train_MLE()
File "run.py", line 94, in train_MLE
encoder_input, decoder_input, weight = model.get_batch(d_valid, i)
File "C:\Users\Kriti Gupta\Desktop\GitHub_repo\Seq2seq-Chatbot-With-Deep-Reinforcement-Learning\seq2seq_model.py", line 342, in get_batch
encoder_input, decoder_input = random.choice(data[bucket_id])
File "C:\Users\Kriti Gupta\AppData\Local\Programs\Python\Python37\lib\random.py", line 261, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
Below is the code which contains the function
def get_batch(self, data, bucket_id, rand = True, order = False):
# data should be [whole_data_length x (source, target)]
# decoder_input should contain "GO" symbol and target should contain "EOS" symbol
encoder_size, decoder_size = self.buckets[bucket_id]
encoder_inputs, decoder_inputs = [], []
#print(bucket_id)
print(random.choice(data[bucket_id]))
encoder_input, decoder_input = random.choice(data[bucket_id])
c = 0
for i in xrange(self.batch_size):
if rand:
encoder_input, decoder_input = random.choice(data[bucket_id])
if order:
encoder_input, decoder_input = data[bucket_id][i]
c += 1
Please help!!
random.choice always raises IndexError on an empty sequence. I would suggest checking the data you are passing to the function
get_batch()
You can also add an 'if condition' in 'get_batch()' method to check if the data passed is empty or not.
Reference:
Python Bug Tracker
I have a scrapy script that works locally, but when I deploy it to Scrapinghub, it's giving all errors. Upon debugging, the error is coming from Yielding the item.
This is the error I get.
ERROR [scrapy.utils.signal] Error caught on signal handler: <bound method ?.item_scraped of <sh_scrapy.extension.HubstorageExtension object at 0x7fd39e6141d0>> Less
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
result = f(*args, **kw)
File "/usr/local/lib/python2.7/site-packages/pydispatch/robustapply.py", line 55, in robustApply
return receiver(*arguments, **named)
File "/usr/local/lib/python2.7/site-packages/sh_scrapy/extension.py", line 45, in item_scraped
item = self.exporter.export_item(item)
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 304, in export_item
result = dict(self._get_serialized_fields(item))
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 75, in _get_serialized_fields
value = self.serialize_field(field, field_name, item[field_name])
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 284, in serialize_field
return serializer(value)
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 290, in _serialize_value
return dict(self._serialize_dict(value))
File "/usr/local/lib/python2.7/site-packages/scrapy/exporters.py", line 300, in _serialize_dict
key = to_bytes(key) if self.binary else key
File "/usr/local/lib/python2.7/site-packages/scrapy/utils/python.py", line 117, in to_bytes
'object, got %s' % type(text).__name__)
TypeError: to_bytes must receive a unicode, str or bytes object, got int
It doesn't specify the field with issues, but by process of elimination, I came to realize it's this part of the code:
try:
item["media"] = {}
media_index = 0
media_content = response.xpath("//audio/source/#src").extract_first()
if media_content is not None:
item["media"][media_index] = {}
preview = item["media"][media_index]
preview["Media URL"] = media_content
preview["Media Type"] = "Audio"
media_index += 1
except IndexError:
print "Index error for media " + item["asset_url"]
I cleared some parts up to make it easier to tackle, but basically this part is the issue. Something it doesn't like about the item media.
I'm beginner in both Python and Scrapy. So sorry if this turns out to be silly basic Python mistake. Any idea?
EDIT: So after getting the answer from ThunderMind, the solution was to simply do str(media_index) for key
Yeah, right here:
item["media"][media_index] = {}
media_index is a mutable. and Keys can't be mutable.
Read Python dict, to know what should be used as keys.
I have to insert approx. 30000 rows daily in my postgres database,
I have 4 columns in my database namely :
id(pkey), category, createddate, updatedon.
My requirement is to update updatedon and category column with today's date and new category if id is present, else insert a new row with createddate and updateon being same.
I found Ilja Everilä's [answer]:https://stackoverflow.com/a/44865375/5665430 for batch update
insert_statement = sqlalchemy.dialects.postgresql.insert(id_tag)
upsert_statement = insert_statement.on_conflict_do_update(
constraint='id',
set_={ "createddate": insert_statement.excluded.createddate }
)
insert_values = df.to_dict(orient='records')
conn.execute(upsert_statement, insert_values)
Its throwing AttributeError,
Traceback (most recent call last):
File "<ipython-input-60-4c5e5e0daf14>", line 5, in <module>
set_= dict(createddate = insert_statement.excluded.createddate)
File "/home/bluepi/anaconda2/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 764, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/home/bluepi/anaconda2/lib/python2.7/site-packages/sqlalchemy/dialects/postgresql/dml.py", line 43, in excluded
return alias(self.table, name='excluded').columns
File "/home/bluepi/anaconda2/lib/python2.7/site-packages/sqlalchemy/sql/selectable.py", line 161, in alias
return _interpret_as_from(selectable).alias(name=name, flat=flat)
AttributeError: 'TextClause' object has no attribute 'alias'
I have tried one by one update as shown here http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#postgresql-insert-on-conflict , but I am getting the same error.
Please help me understand where I am going wrong, thanks in advance.
From your comment
id_tag is nothing but mane of my table in postgres
one could deduce that id_tag is bound to a string. If you'd provided a Minimal, Complete, and Verifiable example, there'd been a lot less guesswork. As it turns out, postgresql.dml.insert() automatically wraps passed strings in a text() construct, and the result when trying to use Insert.excluded is:
In [2]: postgresql.insert('fail').excluded
~/sqlalchemy/lib/sqlalchemy/sql/selectable.py:43: SAWarning: Textual SQL FROM expression 'fail' should be explicitly declared as text('fail'), or use table('fail') for more specificity (this warning may be suppressed after 10 occurrences)
{"expr": util.ellipses_string(element)})
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-f176aac8b913> in <module>()
----> 1 postgresql.insert('fail').excluded
~/sqlalchemy/lib/sqlalchemy/util/langhelpers.py in __get__(self, obj, cls)
765 if obj is None:
766 return self
--> 767 obj.__dict__[self.__name__] = result = self.fget(obj)
768 return result
769
~/sqlalchemy/lib/sqlalchemy/dialects/postgresql/dml.py in excluded(self)
41
42 """
---> 43 return alias(self.table, name='excluded').columns
44
45 #_generative
~/sqlalchemy/lib/sqlalchemy/sql/selectable.py in alias(selectable, name, flat)
159
160 """
--> 161 return _interpret_as_from(selectable).alias(name=name, flat=flat)
162
163
AttributeError: 'TextClause' object has no attribute 'alias'
So, instead of passing a string containing the name of your table to postgresql.dml.insert() pass it an actual Table object, or a light weight table() construct that has been populated with column() objects.