OpenERP/Odoo: fields.datetime.now() show the date of the latest restart - python

I have a field datetime. This field should have by default the datetime of "now", the current time.
However, the default date is the time of the lastest restart.
Please find below my code:
'date_action': fields.datetime('Date current action', required=False, readonly=False, select=True),
_defaults = {
'date_action': fields.datetime.now(),

You are setting the default value of date_action as the value returned by fields.datetime.now(), that is executed when odoo server is started.
You should set the default value as the call to the method:
'date_action': fields.datetime.now,

try to use lambda
For example in Odoo 8 :
date_action = fields.Datetime(string="Date current action", default=lambda *a: datetime.now())

Related

Status update on bulk elastic upload using helper

I am trying to update a bunch of records in a single index, however i need the status if the update is successful or not. Reason is that the particular id may not be available in the index. This is how my code looks like, i dont get any output for "update_response" even though the records are being updated in my index. Shouldnt i be getting a " It returns a tuple with summary information - number of successfully executed actions and either list of errors or number of errors if stats_only is set to True."
as per function definition at this page https://elasticsearch-py.readthedocs.io/en/7.x/helpers.html
es = config.createESConnection()
start_time = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
api_url = 'abcd'
parameters = {
"processed":False,
"date":start_time
}
response = requests.get(api_url,params=parameters)
info= requests.get(api_url,params=parameters).json()['data']
es_data=[]
for i in range(len(info)):
action = {
"_index": "index",
"_id" : info[i]['id'],
"_op_type":"update",
"doc":{"x" : info[i]['x']}
}
es_data.append(action)
update_response = helpers.bulk(es, es_data,stats_only =True)
print(update_response)
except Exception:
okay so this is to help others, in case there is an error in helpers.bulk you need to enable raise_on_error=False, doing so will complete the updation on all the records, skipping the ones having error and then you get the return object.
so use this
update_response = helpers.bulk(es, es_data,raise_on_error=False)

Odoo - Function to get data / value when we open a specific menu

Is there any function that can be used to get and check the data every time a specified menu is loaded/opened?
I have 1 field in the appointment module (time). What I want is when I open the appointment menu, a function will try to get/check all the data in appointment, then later the time field will be filled in according to the code I have made. So every time I open the appointments menu, odoo will check the existing data, and the time field data can be updated.
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(MyMenu, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
data = self.env['appointment.appointment'].search([])
for record in data:
 app = self.env['appointment.time'].search([('time1','<=',record.time),('time2','>=',record.time)], limit=1)
if duration:
record.time_final= app.name + "o'clock"
return res
I have tried the code above, but it only runs 1 time (when I restarted the odoo server).

In odoo 10, using the UI I cannot get my "Server action +Automated action" to work

I have the "reviewer" field available in my task, and I want to switch the reviewer with the task assignee automatically when the task is moved from the 'In progress' stage to the 'Review' stage. I have the following Python code in my server action:
picture of the code in context
def assignrev(self):
for record in self:
if record['project.task.type.stage_id.name']=='Review':
a=self.res.users.reviewer_id.name
b=self.res.users.user_id.name
record['res.users.user_id.name']=a
record['res.users.reviewer_id.name']=b
and below are links to pictures of my automated action settings:
Server action to run
"When to run" settings
Unfortunately, changing the task stage to 'Review' does not give the expected results. Any suggestion please?
Kazu
Ok I finally got the answer to this. below is a picture of the code in context for Odoo 10:
No "def" of "for record" needed: the code will not run.
I just hope this will be helpful to someone else...
Kazu
My guess is that you are incorrectly calling the fields you're trying to get.
# Instead of this
a = self.res.users.reviewer_id.name
b = self.res.users.user_id.name
record['res.users.user_id.name']=a
record['res.users.reviewer_id.name']=b
# Try this
# You don't need to update the name, you need to update the database ID reference
record['user_id'] = record.reviewer_id.id
record['reviewer_id'] = record.user_id.id
Furthermore, why don't you try using an onchange method instead?
#api.multi
def onchange_state(self):
for record in self:
if record.stage_id.name == 'Review':
record.update({
'user_id': record.reviewer_id.id,
'reviewer_id': record.user_id.id,
})
If you're still having problems, you can use ipdb to debug your code more easily by triggering set_trace in your method.
def assignrev(self):
# Triggers a break in code so that you can debug
import ipdb; ipdb.set_trace()
for record in self:
# Test line by line with the terminal to see where your problem is

Web2py: Limiting a dropdown value only to Logged in user

I am trying this form a while. I have a page which displays a form and whose databse definition looks like:
db.define_table('nskrelease',
Field('sprid',length=128,requires=IS_IN_SET(['R3.2', 'R3.3', 'R3.4'],zero=T('choose one'),error_message='must be R3.2 or R3.3 or R3.4 '),label = T('SPR')),
Field('releaseid',length=128, requires = IS_NOT_EMPTY(error_message='Release ID cant be empty'),label = T('Release')),
Field('coordinator',requires=IS_EMAIL(error_message='invalid email!') ,label=T('Co-ordinator Email')),
Field('startdate', 'datetime', default=request.now,requires = IS_NOT_EMPTY(error_message='Start date cant be empty'), label=T('Start date')),
Field('enddate', 'datetime', default=request.now, requires = IS_NOT_EMPTY(error_message='End date cant be empty'), label=T('End Date')),format='%(%releaseid)s')
db.nskrelease.releaseid.requires = IS_NOT_IN_DB(db,'nskrelease.releaseid')
db.nskrelease.coordinator.requires = IS_IN_DB(db,'auth_user.email','%(email)s')
But the problem here is the Coordinator field displays all the user in present in db.auth_user. Instead i need that to be restricted only to the Logged in user. So I tried:
db.nskrelease.coordinator.requires = IS_IN_DB(db(db.nskrelease.coordinator == 'auth.user.email'))
But it gives me error:
TypeError: __init__() takes at least 3 arguments (2 given)
Please help. Thanks in advance.
If the only email address allowed in this field is that of the currently logged in user, then maybe just set that as the default value and don't make the field writable:
Field('coordinator', writable=False,
default=auth.user.email if auth.user else None,
update=auth.user.email if auth.user else None)
However, a better approach might be to make this a reference field, so you don't have to worry about updating this field whenever there is a profile update:
Field('coordinator', 'reference auth_user', writable=False,
default=auth.user_id, represent=lambda v, r: v.email)

Filtering statistics from facebook ads api using the python sdk

I am trying to use Facebook's ads-api to get data about advertising accounts/campaigns/etc within a specified time range.
Up until now I managed to get overall information (added below) using the official python sdk ,
but I can't figure out how to insert the time filter condition.
The answer is probably here under "Filtering results", but I don't understand how to translate what they are doing there to python...
https://developers.facebook.com/docs/reference/ads-api/adstatistics/v2.2
I would really appreciate any help you can provide,
Thanks!
This is the relevant module (I think) from the official python sdk project:
https://github.com/facebook/facebook-python-ads-sdk/blob/master/facebookads/objects.py
My current code is:
from facebookads.session import FacebookSession
from facebookads.api import FacebookAdsApi
from facebookads import objects
from facebookads.objects import (
AdUser,
AdCampaign,
)
my_app_id = 'APP_ID'
my_app_secret = 'AP_SECRET'
my_access_token = 'ACCESS_TOKEN'
my_session = FacebookSession(my_app_id, my_app_secret, my_access_token)
my_api = FacebookAdsApi(my_session)
FacebookAdsApi.set_default_api(my_api)
me = objects.AdUser(fbid='me')
my_accounts = list(me.get_ad_accounts())
my_account=my_accounts[1]
print(">>> Campaign Stats")
for campaign in my_account.get_ad_campaigns(fields=[AdCampaign.Field.name]):
for stat in campaign.get_stats(fields=[
'impressions',
'clicks',
'spent',
'unique_clicks',
'actions',
]):
print(campaign[campaign.Field.name])
for statfield in stat:
print("\t%s:\t\t%s" % (statfield, stat[statfield]))
and the output I get is (All caps and xxxx are mine):
Campaign Stats
CAMPAIGN_NAME1
impressions: xxxx
unique_clicks: xxxx
clicks: xxxx
actions: {u'mobile_app_install': xxxx, u'app_custom_event': xxxx, u'app_custom_event.fb_mobile_activate_app': xxx}
spent: xxxx
CAMPAIGN_NAME2
impressions: xxxx
unique_clicks: xxxx
clicks: xxxx
actions: {XXXX}
spent: xxxx
The get_stats() method has an additional parameter named params where you can pass in start_time and/or end_time.
params_data = {
'start_time': 1415134405,
}
stats = campaign.get_stats(
params=params_data,
fields=[
'impressions',
'clicks',
...
]
)
for stat in stats:
...
The API accepts a number of different parameters documented here: https://developers.facebook.com/docs/reference/ads-api/adstatistics
More optional reading
The reason for both a params parameter and fields parameter requires a bit of explanation. Feel free to ignore this if you're not interested. :)
The implementation for the params parameter basically just constructs the query string for the API call:
params['start_time'] = 1415134405
creates:
?start_time=1415134405
The Ads API endpoints generally accept a fields parameter to define what data you want to return:
?fields=impressions,clicks&start_time=1415134405
which you have correctly defined, but because it's just fields in the query string, you could also technically do this:
params['fields'] = 'impressions,clicks'
The fields parameter in get_stats() (and other read methods) is simply an easy way to define this fields parameter. The implementation looks something like this:
def remote_read(self, params=[], fields=[]):
...
params['fields'] = fields
...
The "get_stats" method is deprecated in the V2.4 version of the API.
Instead, "get_insights" method should be used. The parameters for that method are liste on the page below:
https://developers.facebook.com/docs/marketing-api/insights/v2.5
From the page above, the replacement for the "start_time" and "end_time" is the "time_ranges" attribute. Example:
"time_ranges": {'since': '2015-01-01', 'until': '2015-01-31'}

Categories

Resources