Odoo allow administrator to see all record in tree view - odoo

In tree view I show record where is user_id = uid and for that use:
<field name="domain">[('user_id.id','=',uid)]</field>
I need allow administrator to see all record without domain filter.
Any simple solution?

You can do it using following method.
Remove domain from the action & Inherit search method in python file.
from openerp import models,fields,api,_
from openerp.exceptions import Warning
from openerp.osv import expression
from openerp import SUPERUSER_ID
class mail_message(models.Model):
_inherit = 'mail.message'
def _search(self, cr, uid, args, offset=0, limit=None, order=None,
context=None, count=False, access_rights_uid=None):
""" Override that adds specific access rights of mail.message, to restrict
messages to published messages for public users. """
if uid!=SUPERUSER_ID:
args = expression.AND([[('user_id', '=',uid)], list(args)])
return super(mail_message, self)._search(cr, uid, args, offset=offset, limit=limit, order=order,
context=context, count=count, access_rights_uid=access_rights_uid)
When action will execute _search will be called, in which you can check
if user_id is SUPERUSER_ID then do not add domain or add domain.
This may help you.

Related

Integrating custom module with odoo website

I have a custom module called admission form with some fields suppose name, phone, email, etc. how to add this form to website module using templatr to work like contact form in contact us page when filled data is automatically created in new leads. instead of leads i want it to transfer the information to my custom module.
Summary: instruction to relate website to custom module.
class AdmissionForm(models.Model):
_name = 'admission.form'
name = fields.Char()
phone = fields.Integer()
email = fields.Char()
faculty = field.Many2one('res.faculty')
In ODOO Whenever you want to performe some task at the time of creation ,then you must override create method in your model (:admission.form).
Let say you want to create a partner just after creation of the record in admission.form model then follow these steps:
Override create method .
Call the super with the argument and hold it value in result.
Now do your task .
return result.
Code snippet:
#api.model
def create(self, vals):
result = super(AdmissionForm, self).create(vals)
new_vals = dict(name=result.name,
phone=result.phone,
email=result.email,
is_company=1,
supplier=1,
customer=1,
)
self.env['res.partner'].create(new_vals)
return result
In case if you want to do some task before creation of record then follow these steps:
Override create method .
Do your task .
Call the super with the argument and return it.
#api.model
def create(self, vals):
new_vals = dict(name=vals.get('name'),
phone=vals.get('phone'),
email=vals.get('email'),
is_company=1,
supplier=1,
customer=1,
)
partner=self.env['res.partner'].create(new_vals)
return super(AdmissionForm, self).create(vals)

How to post a message in chatter during create method in Odoo?

I was writing create method for my own custom module.
def create(self, cr, uid,ids, context=None):
self.message_post(cr, uid, ids, body=_("Form Page created"), context=None)
but i am getting the following error when saving
AssertionError: Invalid thread_id; should be 0, False, an ID or a list with one ID
or sometimes
TypeError: create() got multiple values for keyword argument 'context'
i just want to post a message when it is created
Openerp 7 Create Method
def create(self, cr, uid, vals, context=None):
new_id = super(CRM_Lead, self).create(cr, uid, vals, context=context)
return new_id
odoo 8 Create Method:
class ClassName(models.Model):
_inherit = "model.name"
#api.model
def create(self, vals):
rec = super(ClassName, self).create(vals)
# ...
return rec
Make sure you use the exact name of the python class in the super function and also that you return the same object you get from it.
Track Visibility
You can set a mail.message.subtype that depends on an other to act through a relation field.
For better understanding track visibilty Refer This Link
There is two type fileds of track visibility
track_visibility='always'
track_visibility='onchange'

Passing context to qweb report for managing table visibility - odoo

How can we pass context value to qweb report so that i can control the visibility of tables. I have a qweb report with lot of tables. Depending on the selection list, i want to control the view of these tables in qweb report. So my option was to control using context. But didn't find any way to pass the context. If there is any other opinion, please share.
Create parser class first
import time
from openerp.osv import osv
from openerp.report import report_sxw
class sale_quotation_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(sale_quotation_report, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
‘key’: value,
‘function_name’: self.function_name,
})
def function_name(self):
### add some code if required..
Then define another class
class report_saleorderqweb(osv.AbstractModel):
_name = ‘module_name.report_sale_order_qweb’
_inherit = ‘report.abstract_report’
_template = ‘module_name.report_sale_order_qweb’
_wrapped_report_class = sale_quotation_report
Then you can call the localcontext method in that way
<span t-esc=”function_name(parameter)”/>
Refer our blog on Qweb report
Your question is not very clear on what exactly you want. For instance, I dont know what you mean by "Depending on the selection list", so I assume you have a wizard that prompts the user to select some options. If that is the case, you can pass the selection variable inside the data dictionary in the return statement of your print function.
def print_report(self, cr, uid, ids, context=None):
if context is None:
context = {}
datas = {'ids': context.get('active_ids', [])}
res = self.read(cr, uid, ids, ['date_start', 'date_end', 'user_ids'], context=context)
res = res and res[0] or {}
datas['form'] = res
if res.get('id',False):
datas['ids']=[res['id']]
return self.pool['report'].get_action(cr, uid, [], 'point_of_sale.report_detailsofsales', data=datas, context=context)
This passes the user selection under data['form']. You can then access the selections in qweb as data['form']['date_start']

Django Rest Framework custom permissions per view

I want to create permissions in Django Rest Framework, based on view + method + user permissions.
Is there a way to achieve this without manually writing each permission, and checking the permissions of the group that the user is in?
Also, another problem I am facing is that permission objects are tied up to a certain model. Since I have views that affect different models, or I want to grant different permissions on the method PUT, depending on what view I accessed (because it affects different fields), I want my permissions to be tied to a certain view, and not to a certain model.
Does anyone know how this can be done?
I am looking for a solution in the sort of:
Create a Permissions object with the following parameters: View_affected, list_of_allowed_methods(GET,POST,etc.)
Create a Group object that has that permission associated
Add a user to the group
Have my default permission class take care of everything.
From what I have now, the step that is giving me problems is step 1. Because I see no way of tying a Permission with a View, and because Permissions ask for a model, and I do not want a model.
Well, the first step could be done easy with DRF. See http://www.django-rest-framework.org/api-guide/permissions#custom-permissions.
You must do something like that:
from functools import partial
from rest_framework import permissions
class MyPermission(permissions.BasePermission):
def __init__(self, allowed_methods):
super().__init__()
self.allowed_methods = allowed_methods
def has_permission(self, request, view):
return request.method in self.allowed_methods
class ExampleView(APIView):
permission_classes = (partial(MyPermission, ['GET', 'HEAD']),)
Custom permission can be created in this way, more info in official documentation( https://www.django-rest-framework.org/api-guide/permissions/):
from rest_framework.permissions import BasePermission
# Custom permission for users with "is_active" = True.
class IsActive(BasePermission):
"""
Allows access only to "is_active" users.
"""
def has_permission(self, request, view):
return request.user and request.user.is_active
# Usage
from rest_framework.views import APIView
from rest_framework.response import Response
from .permissions import IsActive # Path to our custom permission
class ExampleView(APIView):
permission_classes = (IsActive,)
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
I took this idea and got it to work like so:
class genericPermissionCheck(permissions.BasePermission):
def __init__(self, action, entity):
self.action = action
self.entity = entity
def has_permission(self, request, view):
print self.action
print self.entity
if request.user and request.user.role.access_rights.filter(action=self.action,entity=self.entity):
print 'permission granted'
return True
else:
return False
I used partially in the decorator for the categories action in my viewset class like so:
#list_route(methods=['get'],permission_classes=[partial(genericPermissionCheck,'Fetch','Categories')])
def Categories(self, request):
"access_rights" maps to an array of objects with a pair of actions and object e.g. 'Edit' and 'Blog'

How to access in module - OpenERP web/http.py methods

In openerp 6.1 windows I tried to capture public IP address when people sign-in and sign-out from the HR module. So, in the hr_attendance module I've added ip_address field. Client Public IP address available in the web\common\http.py environ['REMOTE_ADDR']
from osv import fields, osv
from web.common.http import Root
class hr_attendance(osv.osv):
def _get_ipaddress(self, cr, uid, context=None):
ip = None
try:
# environ['REMOTE_ADDR'] how to get
except Exception, e:
pass
return ip
_inherit = "hr.attendance"
_columns = {
'ip_address' : fields.char('IP Address', readonly=True, size=64)
}
_defaults = {
'ip_address': _get_ipaddress,
}
hr_attendance()
How can I get the client IP address or environ['REMOTE_ADDR"] in the default method? Which class and method do I need to override in hr_attendance module?
In my doubt is which method need to call in http.py and what are the parameter to pass get environ['REMOTE_ADDR'] in the HR Module
That looks like it might be difficult to do without changes to the web layer, because the module code doesn't really know anything about the web server layer. The best I could find after a few minutes of digging was a place where you could copy the IP address from the HTTP request to the OpenERP context dictionary. I think if you added this line to the WebRequest.init() method, it might do what you need.
self.context['remote_addr'] = self.httprequest.remote_addr
I think that context will be passed down to the module code where you can read it.