How to update a record from another function - python

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

Related

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)

Python places escape symbols in the Swagger web services response

I have an store procedure Oracle that returns a variable type CLOB with information in JSON format. That variable caught her in a Python
and I return it for a Web Service. The store procedure output is of this style:
{"role":"Proof_Rol","identification":"31056235002761","class":"Proof_Clase","country":"ARGENTINA","stateOrProvince":"Santa Fe","city":"Rosario","locality":"Rosario","streetName":"Brown","streetNr":"2761","x":"5438468,710153","y":"6356634,962204"}
But at the Python service exit it is shown as follows:
{"Atributos": "{\"role\":\"Proof_Rol\",\"identification\":\"31056235002761\",\"class\":\"Proof_Clase\",\"country\":\"ARGENTINA\",\"stateOrProvince\":\"Santa Fe\",\"city\":\"Rosario\",\"locality\":\"Rosario\",\"streetName\":\"Brown\",\"streetNr\":\"2761\",\"x\":\"5438468,710153\",\"y\":\"6356634,962204\"}"}
Does anyone know how to prevent the escape characters from entering that string at the exit of the service?
Part of my Python Code is:
api = Api(APP, version='1.0', title='attributes API',
description='Attibute Microservice\n'
'Conection DB:' + db_str + '\n'
'Max try:' + limite)
ns = api.namespace('attributes', description='Show descriptions of an object')
md_respuesta = api.model('attributes', {
'Attribute': fields.String(required=True, description='Attribute List')
})
class listAtriClass:
Attribute = None
#ns.route('/<string:elementId>')
#ns.response(200, 'Success')
#ns.response(404, 'Not found')
#ns.response(429, 'Too many request')
#ns.param('elementId', 'Id Element (ej:31056235002761)')
class attibuteClass(Resource):
#ns.doc('attributes')
#ns.marshal_with(md_respuesta)
def post(self, elementId):
try:
cur = database.db.cursor()
listOutput = cur.var(cx_Oracle.CLOB)
e, l = cur.callproc('attributes.get_attributes', (elementId, listOutput))
except Exception as e:
database.init()
if database.db is not None:
log.err('Reconection OK')
cur = database.db.cursor()
listOutput = cur.var(cx_Oracle.CLOB)
e, l = cur.callproc('attributes.get_attributes', (elementId, listOutput))
print(listOutput)
else:
log.err('Conection Fails')
listOutput = None
result = listAtriClass()
result.Attribute =listOutput.getvalue()
print(result.Attribute)
return result, 200
Attribute is defined to render as a fields.String but actually it should be defined to render as fields.Nested.
attribute_fields = {
"role": fields.String,
"identification": fields.String,
"class": fields.String,
# ...you get the idea.
}
md_respuesta = api.model('attributes', {
'Attribute': fields.Nested(attribute_fields)
})
Update for flask-restplus
In flask-restplus, a nested field must also register a model.
attribute_fields = api.model('fields', {
"role": fields.String,
"identification": fields.String,
"class": fields.String,
# ...you get the idea.
})
Another way is to inline attribute_fields instead of registering a separate model for it.
md_respuesta = api.model('attributes', {
'Attribute': {
'role': fields.String,
'identification': fields.String,
'class': fields.String,
# ...you get the idea.
}
})

Updating Context in Odoo 8

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

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',
}

Categories