Is there any way to restrict the number of records to be created for a single object or table
My requirement needs me to create only 3 contacts for my company. Is there any way to do so.
Thanks & Regards,
Atchuthan
You can use any one of the following method to restrict the number of records created.
1. Restrict from postgresql-- I dont know how to implement this
2. Restrict from python side.: Override your create method of your model and add check condition, if the limit is reached, then raise a warning.
For example, if you want to only to create max 5 users, then inherit res.users model,
class users(osv.osv):
_inherit="res.users"
def create(cr, uid, default, context=None):
res = super(user, self).create(cr, uid, default, context)
if len(self.search(cr, uid, [])) > 5:
raise osv_except('Error','User Limt exceeded')
return res
By default the limit is 80, however you can change this within this file:
web/addons/web/static/src/js/view_list.js
Full documentation on how to do it is at this website:
http://help.openerp.com/question/6627/how-set-limit-for-number-records-of-x2many/
Related
.py file:
….
namex=fields.Text()
moifier=fields.Many2one(‘res.users’, string=”Modifier”)
…
When some user modify “namex”, his/her name should be recorded on field “modifier” automatically; what code should I make? I try “onchange/depends”, but failed; maybe modifier could be a “text field/ char field”?
in addition, shall I set "access_rule" to set users just see the records created by the members in his/her own group?
Odoo already has that for you. Every model has those fields, which are automatically created and updated each time you create, or write:
create_date (datetime): when record is created
create_uid (many2one): user who created this record
write_date (datetime): last time record is updated
write_uid (many2one): last user updated this record
Go to Settings > Technical > Database Structure > Models for more details.
While Odoo will keep for you a track of the last user which has modified a record, a modifier per field is not kept. I can see the interest of such a functionality in many cases.
To do that for a particular model one possibility is to redefine the write method of this model. In your .py file you may want to add something like this:
#api.model
def write(self):
if self.namex in values:
values.update({'modifier': uid})
super().write(cr, uid, ids, values, context)
Another way to do that in a more flexible way is to use the #onchange decorator:
#onchange('your_sensible_field_name'):
def set_modifier(self):
self.modifer = self.env.user
You may also want to take a look at the #depends decorator.
Say I have User and Subuser tables, where a User can have many Subusers. How can I only allow the logged in user (current_user) to view only the Subusers who are a part of the User? I.e. Subuser.user_id == current_user.id. I get I can do this by a filter, but this must be forced and not optional.
I'm using the SQLAlchemy backend if that helps!
It's pretty simple to override the queries that are produced by the backend in Flask Admin - you can do some quite complex things. Remember to override all of the below - especially get_one().
class BaseModelView(ModelView):
def is_accessible(self):
# if not authenticated we can't see this
if not login.current_user.is_authenticated():
return False
return True
def get_query(self):
return query.filter(self.model.parent_user_id.any(id=login.current_user.id))
def get_count_query(self):
# faster count query!
query = self.session.query(func.count('*')).select_from(self.model).filter(self.model.location_id == login.current_user.id)
return query
def get_one(self, id):
"""
Return a single model by its id.
:param id:
Model id
"""
result = self.session.query(self.model).get(iterdecode(id))
# if the users location does not exist and she is only allowed to edit locations they control
if login.current_user.id != result.parent_user_id:
app.logger.warn('You are not allowed to edit entries for this user.')
abort(404)
return result
can anyone explain the working of create and write orm mehods in openerp ? Actually I'm stuck at this methods,I'm not getting how it works internally and how can I implement it over a simple program.
class dumval(osv.osv):
_name = 'dum_val'
_columns={
'state':fields.selection([('done','confirm'),('cancel','cancelled')],'position',readonly=True),
'name':fields.char('Name',size=40,required=True,states={'done':[('required','False')]}),
'lname':fields.char('Last name',size=40,required=True),
'fname':fields.char('Full name',size=80,readonly=True),
'addr':fields.char('Address',size=40,required=True,help='enter address'),
}
_defaults = {
'state':'done',
}
It would be nice if u could explain using this example..
A couple of comments plus a bit more detail.
As Lukasz answered, convention is to use periods in your model names dum.val. Usually something like my_module.my_model to ensure there are no name collisions (e.g. account.invoice, sale.order)
I am not sure if your conditional "required" in the model will work; this kind of thing is usually done in the view but it would be worth seeing how the field is defined in the SQL schema.
The create method creates new records (SQL Insert). It takes a dict of values, applies any defaults you have specified and then inserts the record and returns the new ID. Note that you can do compound creates, i.e. if you are creating and invoice, you can add the invoice lines into the dictionary and do it all in one create and OpenERP will take care of the related fields for you (ref write method in https://doc.openerp.com/trunk/server/api_models/)
The write method updates existing records (SQL Update). It takes a dict of values and applies to all of the ids you pass. This is an important point, if you pass a list of ids, the values will be written to all ids. If you want to update a single record, pass a list of one entry, if you want to do different updates to the records, you have to do multiple write calls. You can also manage related fields with a write.
It's convention to give _name like dum.val instead of dum_val.
In dumval class you can write a method:
def abc(cr, uid, ids, context=None):
create_dict = {'name':'xxx','lname':'xxx','fname':'xxx','addr':'xyz'}
# create new object and get id
new_id = self.create(cr, uid, write_dict, context=context)
# write on new object
self.write(cr, uid, new_id, {'lname':'yyy'}, context=context)
For more details look: https://www.openerp.com/files/memento/older_versions/OpenERP_Technical_Memento_v0.6.1.pdf
I'm developing an OpenERP 7 module and I need to add a field that logs the user who created each record. How do I retrieve the current user object?
this kind of field is already available in openerp, as create_uid and write_uid.
In OpenERP Python code, functions generally take cr, the database pointer, and uid, the user id, as arguments. If all you need is the id of the current res.users object (for instance, to write into the one2many field), you can use uid as is. If you need to access the object (to see fields, etc.), something like:
current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
should work.
I am trying to create a field from the web gui of OpenERP and field type as reference
1st there is no better docs about reference
2nd what I want is when someone selects the field it should give another option on selection which is not happening (though it is giving some field but 2nd field throws an error)!
It throws an error object does not exist
Reference fields are mainly used for showing different model's records as reference in your record. For example you have created a model such that whenever a sale order, purchase order, delivery order, project etc are created and saved, then a new record with data like user name, date, some notes should be created in your model. So here you add a reference field which link to the original record(sale order, purchase order etc) from which your record is created. You can find this in res.request model in openerp 6
To create an reference field in your class
def _get_selection_list(self, cr, uid, context=None):
##return a list of tuples. tuples containing model name and name of the record
model_pool = self.pool.get('ir.model')
ids = model_pool.search(cr, uid, [('name','not ilike','.')])
res = model_pool.read(cr, uid, ids, ['model', 'name'])
return [(r['model'], r['name']) for r in res] + [('','')]
_columns = {
'ref': fields.reference(Reference', selection=_get_selection_list, size=128)
}