Updating Context in Odoo 8 - python

I am writing a method that it first will retrieve the current context from the model then using context.update() to add on new values for the context. I also tried to use the current method self.with_context() but still no success since the context values seem frozen and could not be passed in. I read online from some source that there is a way to override the name_get(). But the source only briefly reference, there would be no clear instruction so that i can follow. I am new in Odoo and the problem between v7 and v8 its killing me. Please help me revise my following source code:
def get_print_report(self):
domain = [('effective_date', '>=', self.from_date),
('effective_date', '<=', self.to_date),
('employee_id', 'in', self.employee_ids.ids),
('department_id', '=', self.department_id.id),
('job_id', '=', self.job_id.id)]
list_view = self.env.ref(
'trainingwagekp.payroll_wage_hist_wizard_tree_view')
context = self._context.copy()
if context is None:
context = {}
if context.get('order_by', False):
context.update({'default_order': self.order_by + ' desc'})
self.with_context(context)
print '===============', self._context
return{'name': 'Wage History Report',
'view_type': 'form',
'view_mode': 'tree',
'view_id': list_view.id,
'res_model': 'trobz.payroll.wage.history',
'type': 'ir.actions.act_window',
'context': context,
'domain': domain,
}
Please also let me know which is the best way to modify context in Odoo 8. Thanks

You already passing new context in return. Just remove self.with_context(context) line. As per below code.
def get_print_report(self):
domain = [('effective_date', '>=', self.from_date),
('effective_date', '<=', self.to_date),
('employee_id', 'in', self.employee_ids.ids),
('department_id', '=', self.department_id.id),
('job_id', '=', self.job_id.id)]
list_view = self.env.ref(
'trainingwagekp.payroll_wage_hist_wizard_tree_view')
context = self._context.copy()
if context is None:
context = {}
if context.get('order_by', False):
context.update({'default_order': self.order_by + ' desc'})
return{'name': 'Wage History Report',
'view_type': 'form',
'view_mode': 'tree',
'view_id': list_view.id,
'res_model': 'trobz.payroll.wage.history',
'type': 'ir.actions.act_window',
'context': context,
'domain': domain,
}

I think if you check the type of context, you will find that it is a frozen dict. You shall change it to a dict context = dict(self._context) then do all the alteration you need then turn it back into a frozen dict and give

Related

How to update a record from another function

I'm trying to update the body field from the payrun_chatter_log() but it won't update. any idea on how to do this? This is what I did:
def payrun_chatter_log(self):
subtype = self.env['mail.message.subtype'].search([('id','=', '2')])
vals = {
'date': fields.datetime.now(),
'email_from': self.env.user.email_formatted,
'author_id': self.env.user.id,
'message_type': 'notification',
'subtype_id': subtype.id,
'is_internal': True,
'model': 'custom.module',
'res_id': self.id,
'body': 'Test'
}
self.env['mail.message'].create(vals)
def custom_button(self):
chatter = self.env['mail.message'].search([('res_id', '=', self.id)])
message = 'Custom Message here'
chatter.update({'body': message})
return super(CustomModule, self).custom_button()
Your below line of code in custom_button will return multi record because res_id will be repeated for more than one model
chatter = self.env['mail.message'].search([('res_id', '=', self.id)])
You need to add the model to search:
chatter = self.env['mail.message'].search([('model', '=', self._name), ('res_id', '=', self.id)])
The message body should be updated, you need to refresh the page to see the changes.
Try to return the following client action:
return {
'type': 'ir.actions.client',
'tag': 'reload',
}
The chatter has an One2many relation to mail.message model. Your function will update all messages

Pass list records to many2many field in odoo

I've created a wiz to get the product which are in the field "catagory_select" please look the code below:
class CategorySelect(models.TransientModel):
_name = 'product.group'
category_select = fields.Many2many('product.category', string='Category')
def start_search_product(self):
wiz_form = self.env.ref('product_filter.get_products_form_all', False)
for rec in self.category_select:
product_res = self.env['product.product'].search([('categ_id', '=', rec.ids)])
print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^', product_res)
return {
'type': 'ir.actions.act_window',
'name': "Product Filtered",
'res_model': 'product.selection',
'target': 'new',
'view_id': wiz_form.id,
'view_mode': 'form',
}
}
here what i done is i have created a method which returns a wizard but i am not getting a way that how shoud i pass the "product_res" to a many2many field in another wizard which is called the return menu.
"Any help will be appreciated"
You can set on context with default fields set with your values.
ctx = self._context.copy()
ctx.update({'default_m2m_fields': [(6, 0, IDS)]}) # on new wizard the m2m fields set with default on context
You can pass the product_res to another wizard using context
1/ Update your start_search_product to pass the product_res ids:
def start_search_product(self):
product_res_ids = [p.id for p in product_res]
context = {'product_ids': product_res_ids}
return {
'type': 'ir.actions.act_window',
'name': "Product Filtered",
'res_model': 'product.selection',
'target': 'new',
'view_id': wiz_form.id,
'view_mode': 'form',
'context': context,
}
}
2/ Get the product ids in function default_get of ProductSelection wizard:
product_ids = fields.Many2many('product.product', 'Products')
#api.model
def default_get(self, default_fields):
res = super(ProductSelection, self).default_get(default_fields)
product_ids = self._context.get('product_ids')
res.update({'product_ids': [(6, 0, product_ids)]})
return res

Integrating 2checkout with Django 2.2

I try to implement 2checkout to my django app (Python 3.7 and Django 2.2).
I'm using the Sandox and when I see API logs my orders are successfully passed. I also chose a URL for the Passback and selected Header Redirect in my account settings.
Unfortunately, I don't succeed in getting the redirection works :
I get this error after twocheckout.Charge.authorize(params) if successfully executed:
The view subscriptions.views.subscription_payment didn't return an HttpResponse object. It returned None instead.
When I manually add an HttpResponseRedirect like this:
return HttpResponseRedirect('/payment-success') the GET request is empty because it doesn't come from 2checkout.
I tried to follow this tutorial https://github.com/2Checkout/2checkout-python-tutorial and it doesn't mention any HttpResponseRedirect.
Could you please help me with this issue? It's really frustrating. I'm a beginner developper so maybe I missed something. Please feel free to ask any further information that would be helpful to understand my issue.
Many thanks in advance
I was integrating the API so no need for Passback URL. The question was a non sense :) That's why the tutorial doesn't mention HttpResponseRedirect.
Because it has been asked in the comments, here is the code used to fulfil the need I had at that moment. Hope this could help someone else.
def subscription_payment(request, pk):
property = Property.objects.get(pk=pk)
if request.method == 'POST':
pay_token = request.POST.get('token')
twocheckout.Api.auth_credentials({
'private_key': '######-####-####-####-#######',
'seller_id': '#########',
'mode': 'sandbox' # Uncomment to use Sandbox
})
data = serializers.serialize('json', Profile.objects.filter(user=request.user), fields=(
'address_2', 'city', 'zip_code', 'country', 'phone_number'))
data = json.loads(data)
params = {
'merchantOrderId': request.user.id,
'token': pay_token,
'currency': 'USD',
'billingAddr': {
'name': request.user.get_full_name(),
'addrLine1': data[0]['fields']['address_2'],
'city': data[0]['fields']['city'],
'state': ' ',
'zipCode': data[0]['fields']['zip_code'],
'country': data[0]['fields']['country'],
'email': request.user.email,
'phoneNumber': data[0]['fields']['phone_number'],
},
'lineItems': [
{
'type': 'product',
'name': 'Abonnement mensuel basic',
'recurrence': '1 Month',
'duration': '3 Month',
'tangible': 'N',
'price': '150.00',
'description': '',
'productId': property.id,
}
]
}
try:
result = twocheckout.Charge.authorize(params)
backup_response = json.dumps(result)
print(result.responseCode)
if result.responseCode == 'APPROVED':
offer = Offer.objects.get(type='MONTHLY_BASIC')
user = request.user
payment_data = dict()
payment_data['response_code'] = result.responseCode
payment_data['transaction_id'] = result.transactionId
payment_data['order_number'] = result.orderNumber
payment_data['amount'] = result['lineItems'][0]['price']
payment_data['property_title_bkp'] = property.title
payment_data['backup_response'] = backup_response
Payment.objects.create(
offer=offer,
property=property,
user=user,
initiated_on=timezone.now(),
**payment_data
)
return render(request, 'subscriptions/payment_success.html', payment_data)
except TwocheckoutError as error:
return HttpResponse(error.msg)

Print params in report from a wizard

I'm trying to get a report from wizard, I'm pointing to mi res_model:stock.quant from my return:
def print_report(self, cr, uid, ids, context=None):
datas = {'partner' : context.get('cliente'), 'mounth':context.get('mes')}
return {
'type': 'ir.actions.report.xml',
#~ 'report_file': 'stock.uas.wizard',
'report_name': 'stock.report_uas_document',
'report_type': 'qweb-html',
'datas': datas,
'context': context,
'res_model': 'stock.quant',
'src_model': 'stock.quant',
}
I'm fetching the right model and report, but when y try to consume some field I get this error:
QWebException: "'NoneType' object has no attribute 'get_pallets'" while evaluating
And if I try with some function inside the model I get this error:
QWebException: ('MissingError', you'One of the documents you are trying to access has been deleted, please try again after refreshing.')
Like I am in another model with no field and function named la that.but if a do
<span t-esc="o"/>
In the report
y get: stock.quant(42,)
So the question is, how can I get and consume param from a return.
I think I am in the right object, I build this report in traditional way and its word but through a return call function I don't get pass the param.
Your datas is a dictionary and has only two values.
To do as explained above, try this:
def print_report(self, cr, uid, ids, context=None):
assert len(ids) == 1,
datas = {
'ids': ids,
'model': 'stock.quant',
'form': self.read(cr, uid, ids[0], context=context)
}
return {
'type': 'ir.actions.report.xml',
#~ 'report_file': 'stock.uas.wizard',
'report_name': 'stock.report_uas_document',
'report_type': 'qweb-html',
'datas': datas,
'context': context,
'res_model': 'stock.quant',
'src_model': 'stock.quant',
}

Pop up the window of exsiting view through click event in odoo

I have created a button in jobs by using inheritance in (hr.recruitment form view) , how could I open another module("Resumes and Letters -sub menu in Human Resource " ) form_view during buttons click event is done.my aim is that I just want open that form when this click event done.
Is it possible to solve? Need help please
yes, it is possible to open another window. you have to do like this.
#api.multi
def button_method(self):
return {
'type': 'ir.actions.act_window',
'name': 'form name',
'res_model': 'object name',
'res_id': id ,
'view_type': 'form',
'view_mode': 'form',
'target' : 'new',
}
but it is possible when record save. if you want to open wizard before save record you have to code in js like this.
in js file:
openerp.module_name = function(instance) {
var QWeb = openerp.web.qweb;
_t = instance.web._t;
instance.web.View.include({
load_view: function(context) {
var self = this;
var view_loaded_def;
$('#oe_linking_e').click(this.on_preview_view_button);
//this is button class which call method for open your form.
return self._super(context);
},
//method which open form
on_preview_view_button: function(e){
e.preventDefault();
this.do_action({
name: _t("View name"),
type: "ir.actions.act_window",
res_model: "object",
domain : [],
views: [[false, "list"],[false, "tree"]],
target: 'new',
context: {},
view_type : 'list',
view_mode : 'list'
});
}
},
});
};
in xml file add button and give id="oe_linking_e" whatever you give in js code.
you can return form in this manner.
In your button method return this dictionary. It will open the target form in a pop-up window ,
def button_method(...........):
return {
'name': _(some name),
'view_type': 'form',
"view_mode": 'form',
'res_model': model-name,
'type': 'ir.actions.act_window',
'target': 'new',
}
you can pass <br> 'res_id': target_id in the above dictionary to open a particular record

Categories