Is there a way to add custom field attribute in Odoo? For example every field has attribute help where you can enter message explaining the field for the user. So I want to add custom attribute, so that would change the way field acts for all types of fields.
I want to add into Field class, so all fields would get that attribute. But it seems no matter what I do, Odoo does not see that such attribute was added.
If I simply add new custom attribute like:
some_field = fields.Char(custom_att="hello")
Then it is simply ignored. And I need it to be picked up by method fields_get, which can return wanted attribute value (info what it does:
def fields_get(self, cr, user, allfields=None, context=None, write_access=True, attributes=None):
""" fields_get([fields][, attributes])
Return the definition of each field.
The returned value is a dictionary (indiced by field name) of
dictionaries. The _inherits'd fields are included. The string, help,
and selection (if present) attributes are translated.
:param allfields: list of fields to document, all if empty or not provided
:param attributes: list of description attributes to return for each field, all if empty or not provided
"""
So calling it, does not return my custom attribute (it does return the ones originally defined by Odoo though).
I also tried updating _slots (with monkey patch or just testing by changing source code) attribute in Field class, but it seems it is not enough. Because my attribute is still ignored.
from openerp import fields
original_slots = fields.Field._slots
_slots = original_slots
_slots['custom_att'] = None
fields.Field._slots = _slots
Does anyone know how to properly add new custom attribute for field?
Assuming v9
The result of fields_get is a summary of fields defined on a model, the code shows that it will only add the attribute if the description was filled. It will fetch the description of the current field by calling field.get_description
So in order to ensure that your attribute gets inserted into this self.description_attrs you will need to add an attribute or method that starts with _description_customatt (customatt part from your example) and will return the required data.
I've not run any tests for this but you can look at the code for the fields and their attributes what they actually return. For instance the help attribute description (src)
def _description_help(self, env):
if self.help and env.lang:
model_name = self.base_field.model_name
field_help = env['ir.translation'].get_field_help(model_name)
return field_help.get(self.name) or self.help
return self.help
This is only something you can do if you run OpenERP/ODOO on your own server (in other words, not the cloud version whose code you cannot access).
You will need to modify the <base>/osv/fields.py file and add your changes to the field_to_dict function towards the bottom of the file (the base _column class already saves extra keyword arguments for you -- at least in version 7.0):
def field_to_dict(model, cr, user, field, context=None):
res = {'type': field._type}
...
...
for arg in ('string', 'readonly', ...) :
Somewhere in that long list of attributes you need to insert the name of the one you are interested in.
Alternatively, you could update _column.__init__ to save the names of the extra arguments, and field_to_dict to include them (untested):
diff -r a30d30db3cd9 osv/fields.py
--- a/osv/fields.py Thu Jun 09 17:18:29 2016 -0700
+++ b/osv/fields.py Mon Jun 13 18:11:26 2016 -0700
## -116,23 +116,24 ## class _column(object):
self._context = context
self.write = False
self.read = False
self.view_load = 0
self.select = select
self.manual = manual
self.selectable = True
self.group_operator = args.get('group_operator', False)
self.groups = False # CSV list of ext IDs of groups that can access this field
self.deprecated = False # Optional deprecation warning
- for a in args:
- if args[a]:
- setattr(self, a, args[a])
+ self._user_args = ()
+ for name, value in args:
+ setattr(self, name, value or False)
+ self._user_args += name
def restart(self):
pass
def set(self, cr, obj, id, name, value, user=None, context=None):
cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))
def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
raise Exception(_('undefined get method !'))
## -1559,20 +1560,22 ## def field_to_dict(model, cr, user, field
res['o2m_order'] = field._order or False
if isinstance(field, many2many):
(table, col1, col2) = field._sql_names(model)
res['m2m_join_columns'] = [col1, col2]
res['m2m_join_table'] = table
for arg in ('string', 'readonly', 'states', 'size', 'group_operator', 'required',
'change_default', 'translate', 'help', 'select', 'selectable', 'groups',
'deprecated', 'digits', 'invisible', 'filters'):
if getattr(field, arg, None):
res[arg] = getattr(field, arg)
+ for arg in field._user_args:
+ res[arg] = getattr(field, arg)
if hasattr(field, 'selection'):
if isinstance(field.selection, (tuple, list)):
res['selection'] = field.selection
else:
# call the 'dynamic selection' function
res['selection'] = field.selection(model, cr, user, context)
if res['type'] in ('one2many', 'many2many', 'many2one'):
res['relation'] = field._obj
res['domain'] = field._domain(model) if callable(field._domain) else field._domain
Related
How can i update the same group if the name of group user wants to create matches with already created group? If i want to update instead of showing error where should i work on? Is it on validate function or create function?
Here is my serializer
class DeviceGroupSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(source='token', format='hex', read_only=True)
devices = DeviceIdSerializer(many=True)
class Meta:
model = DeviceGroup
fields = ['id','name', 'devices',]
def validate(self, data):
errors = {}
try:
name = data['name']
if not bool(name):
#empty or null
errors['name'] = 'Name cannot be empty'
except KeyError:
if not (self.instance and bool(self.instance.name)):
errors['name'] = 'Name is required'
if len(data.get('devices', [])) == 0:
errors['devices'] = 'Device(s) should be specified.'
if bool(errors):
raise serializers.ValidationError(errors)
return data
def create(self, validated_data):
# for create - there is always name; we have already checked that in validation
# TODO Further check for group-name clash - if yes, update the same group
owner = validated_data['owner']
name = validated_data['name']
group = DeviceGroup.objects.create(owner=owner, name=name)
tokens = [d['token'] for d in validated_data['devices'] ]
BaseDevice.objects.filter(token__in=tokens, owner=owner).update(group=group)
return group
def update(self, instance, validated_data):
# for update - there may or may not be name
# if it does, it refers rename
owner = validated_data['owner']
name = validated_data.get('name', None)
if not name is None:
instance.update(name=name)
tokens = [d['token'] for d in validated_data['devices'] ]
BaseDevice.objects.filter(token__in=tokens, owner=owner).update(group=instance)
return instance
You want update_or_create():
A convenience method for updating an object with the given kwargs,
creating a new one if necessary. The defaults is a dictionary of
(field, value) pairs used to update the object.
Based on what you've shared, this would look something like the following, assuming you want to update the owner on DeviceGroup, if a DeviceGroup with the given name already exists:
def create(self, validated_data):
# for create - there is always name; we have already checked that in validation
# TODO Further check for group-name clash - if yes, update the same group
owner = validated_data['owner']
name = validated_data['name']
# created is a boolean telling us if a new DeviceGroup was created
group, created = DeviceGroup.objects.update_or_create(name=name, defaults={'owner': owner})
tokens = [d['token'] for d in validated_data['devices'] ]
BaseDevice.objects.filter(token__in=tokens, owner=owner).update(group=group)
return group
I am attempting to push data from a DJANGO view into the Tables object, passing it through as an argument. In this case, I would like to pass a variable called doc_id into a Tables2 object called tableName
In this example, I have set doc_id as 1, and pass it into the
View
def editorView(request):
doc_id = 1
table = tableName(UserProfile.objects.filter(), doc_id=doc_id)
Table
class tableName(tables.Table):
tbl_doc_id = None ## Creating a temporary variable
def __init__(self, *args, **kwargs):
temp = kwargs.pop("doc_id") ## Grab doc_ID from kwargs
super(tableName, self).__init__(*args, **kwargs)
self.tbl_doc_id = temp ## Assign to self.tbl_doc_id for use later
### Do something with tbl_doc_id
modelFilter = model.objects.filter(pk = tbl_doc_id)
When running the debugger, I can see that tbl_doc_id is still assigned as None, rather than 1.
What is the correct way to pass arguments into a Tables2 instance? Is it possible?
EDIT: Adding more information for context.
In the real world scenario, I have a view. That view takes an argument from the URL called doc_id. That doc_id is used to grab an object from a model called 'MaterialCollection', and return it as 'mc'.
'mc' is then passed into the table
View
def editorView(request, doc_id):
try:
mc = MaterialCollection.objects.get(pk = doc_id)
except Material.DoesNotExist:
raise Http404("Document does not exist")
config = RequestConfig(request)
unnassigned_User_Table = unassignedUserTable(UserProfile.objects.filter(), mc=mc)
... Other code + Render ...
From my table, I create a custom LinkColumn. That linkColumn is used to construct a URL based upon a number of Attributes from the model 'UserProfile', and from mc.
Table
class unassignedUserTable(tables.Table):
mc = None
def __init__(self, *args, **kwargs):
temp_mc = kwargs.pop("mc")
super(unassignedUserTable, self).__init__(*args, **kwargs)
self.mc = temp_mc
current_Assignment = "NONE"
new_Assignment = "AS"
assign_Reviewer = tables.LinkColumn('change_Review_AssignmentURL' , args=[ A('user'), current_Assignment, new_Assignment, mc, A('id')], empty_values=(), attrs={'class': 'btn btn-success'})
class Meta:
model = UserProfile
... Setup excludes/sequence/attributes...
In this particular instance. mc has a FK to UserProfile (in a 1:M) relationship.
I see that the name of your table class is tableName so if you want __init__ to work as expected please change the line:
super(unassignedUsers, self).__init__(*args, **kwargs)
to
super(tableName, self).__init__(*args, **kwargs)
Beyond this obvious problem, there are some more issues with your code:
Your classes must start with a capital letter (TableName instead of tableName)
Your table classes should end end with -Table (for example NameTable)
I am using django-tables2 for many years and never needed to pass something in __init__ as you are doing here. Are you sure that you really need to do this?
If you want to filter the table's data the filtering must be done to your view - the table will get the filtered data to display.
I have a need to track changes on Django model instances. I'm aware of solutions like django-reversion but they are overkill for my cause.
I had the idea to create a parameterized class decorator to fit this purpose. The arguments are the field names and a callback function. Here is the code I have at this time:
def audit_fields(fields, callback_fx):
def __init__(self, *args, **kwargs):
self.__old_init(*args, **kwargs)
self.__old_state = self.__get_state_helper()
def save(self, *args, **kwargs):
new_state = self.__get_state_helper()
for k,v in new_state.items():
if (self.__old_state[k] != v):
callback_fx(self, k, self.__old_state[k], v)
val = self.__old_save(*args, **kwargs)
self.__old_state = self.__get_state_helper()
return val
def __get_state_helper(self):
# make a list of field/values.
state_dict = dict()
for k,v in [(field.name, field.value_to_string(self)) for field in self._meta.fields if field.name in fields]:
state_dict[k] = v
return state_dict
def fx(clazz):
# Stash originals
clazz.__old_init = clazz.__init__
clazz.__old_save = clazz.save
# Override (and add helper)
clazz.__init__ = __init__
clazz.__get_state_helper = __get_state_helper
clazz.save = save
return clazz
return fx
And use it as follows (only relevant part):
#audit_fields(["status"], fx)
class Order(models.Model):
BASKET = "BASKET"
OPEN = "OPEN"
PAID = "PAID"
SHIPPED = "SHIPPED"
CANCELED = "CANCELED"
ORDER_STATES = ( (BASKET, 'BASKET'),
(OPEN, 'OPEN'),
(PAID, 'PAID'),
(SHIPPED, 'SHIPPED'),
(CANCELED, 'CANCELED') )
status = models.CharField(max_length=16, choices=ORDER_STATES, default=BASKET)
And test on the Django shell with:
from store.models import Order
o=Order()
o.status=Order.OPEN
o.save()
The error I receive then is:
TypeError: int() argument must be a string or a number, not 'Order'
The full stacktrace is here: https://gist.github.com/4020212
Thanks in advance and let me know if you would need more info!
EDIT: Question answered by randomhuman, code edited and usable as shown!
You do not need to explicitly pass a reference to self on this line:
val = self.__old_save(self, *args, **kwargs)
It is a method being called on an object reference. Passing it explicitly in this way is causing it to be seen as one of the other parameters of the save method, one which is expected to be a string or a number.
I have a data model with a bitfield defined something like this:
alter table MemberFlags add column title varchar(50) not null default '';
alter table MemberFlags add column value integer( 3) not null default 0;
insert into MemberFlags (title, value) values
("Blacklisted", 1),
("Special Guest", 2),
("Attend Ad-hoc Sessions", 4),
("Attend VIP Sessions", 8),
("Access Facility A", 16),
("Access Facility B", 32)
And used like this:
alter table Membership add column title varchar(50) not null default '';
alter table Membership add column flags integer( 3) not null default 0;
insert into Membership (title, flags) values
("Guest Pass", 4+2 ),
("Silver Plan", 16+ 4 ),
("Gold Plan", 32+16+ 4+2 ),
("VIP Pass", 32+16+8+4+2 )
My questions are:
A) What's the easiest way to represent the different bitflags as separate items in the admin site? Should I override the template, or do something with forms?
B) How about the search list? I could create functions in the model to represent each bit, but how would searching and sorting be done?
I'm new to Django.
A great tested solution, even if it doesn't fit your model right away, would be using django-bitfield
I think the best solution here would be for you to create a new field type by subclassing models.Field. You could make use of the choices parameter to assign the valid bit flags and their meanings. This would help keep your model declaration clean and readable, with a final result along the lines of:
class BitFlagField(models.Field):
...
class MyModel(models.Model):
...
FLAG_CHOICES = (
(1, 'Blacklisted'),
(2, 'Special Guest'),
(4, 'Attend Ad-hoc Sessions'),
(8, 'Attend VIP Sessions'),
(16, 'Access Facility A'),
(32, 'Access Facility B'),
)
flags = BitFlagField(choices=FLAG_CHOICES)
...
The Django documentation has a great in-depth article on how to go about subclassing models.Field:
Writing Custom Model Fields
It seems to cover everything you need to do, including:
Specifying Form Field (Tying a form to the field so that django-admin knows how to display it.)
Preparing Values for Lookups (Which will allow you to use the field for searches and filtering.)
If you're looking for an example of a subclassed field, this snippet might be of use. Its goal is similar (multiple choices as a model field), but its manner of storing them in the database differs (it's using a CSV text field instead of bit flags).
Working off the snippet in Andrew's answer, here are the changes you'd need to make:
from django.db import models
from django import forms
class BitFlagFormField(forms.MultipleChoiceField):
widget = forms.CheckboxSelectMultiple
def __init__(self, *args, **kwargs):
super(BitFlagFormField, self).__init__(*args, **kwargs)
class BitFlagField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "Integer"
def get_choices_default(self):
return self.get_choices(include_blank=False)
def _get_FIELD_display(self, field):
value = getattr(self, field.attname)
choicedict = dict(field.choices)
def formfield(self, **kwargs):
# do not call super, as that overrides default widget if it has choices
defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name),
'help_text': self.help_text, 'choices':self.choices}
if self.has_default():
defaults['initial'] = self.get_default()
defaults.update(kwargs)
return BitFlagFormField(**defaults)
def get_db_prep_value(self, value):
if isinstance(value, int):
return value
elif isinstance(value, list):
return sum(value)
def to_python(self, value):
result = []
n = 1
while value > 0:
if (value % 2) > 0:
result.append(n)
n *= 2
value /= 2
return sorted(result)
def contribute_to_class(self, cls, name):
super(BitFlagField, self).contribute_to_class(cls, name)
if self.choices:
func = lambda self, fieldname = name, choicedict = dict(self.choices):" and ".join([choicedict.get(value,value) for value in getattr(self,fieldname)])
setattr(cls, 'get_%s_display' % self.name, func)
This is how I would use the flags with my User class:
FLAGS = {
1:"Blacklisted",
2:"SpecialGuest",
4:"AttendAd-hocSessions",
8:"AttendVIPSessions",
16:"AccessFacilityA",
32:"AccessFacilityB",
}
class User(object):
def __init__(self, name="John Doe", groups=0):
self.name = name
self.groups = groups
def memberof(self):
''' Display string representation of the groups. '''
for flag in sorted(FLAGS):
if (flag & self.groups) == flag:
print FLAGS[flag]
Of course instead of printing the flags, you can create a comma-separated string to display in the admin view, or whatever you desire.
For the admin, just use a boolean for each of the group values.
I'm trying to create a custom timestamp field.
class TimestampKey(models.CharField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
import time
kwargs['unique'] = True
kwargs['max_length'] = 20
kwargs['auto_created'] = True
kwargs['editable']=False
super(TimestampKey, self).__init__(*args, **kwargs)
def to_python(self, value) :
return value
def get_db_prep_value(self, value) :
try:
import time
t = time.localtime()
value = reduce(lambda a,b:str(a)+str(b),t)
except ValueError:
value = {}
return value
class Table1(models.Model):
f = TimestampKey(primary_key=True)
n = ....
It stores the value with appropriate timestamp in the db. But it doesnt populate the field 'f' in the object.
Eg:
t1 = Table1(n="some value")
t1.f -> blank
t1.save()
t1.f -> blank.
This is the problem. Am I missing something so that it doesnt populate the filed?
Please shed some light on this.
Thanks.
Is it wise to use a timestamp as your primary key? If your database uses ISO 8601 or really any time format in which second is the smallest time interval... Well, anyway, my point is that you have no guarantee, especially if this is going to be a web-facing application that two entries are going to resolve within the minimum time interval. That is, if the smallest time interval is a second, as in ISO 8601, if you get two requests to save in the same second, you're going to get an error condition. Why not stick to automatically incrementing integer keys and just make the timestamp its own field?
The get_db_prep_value method only prepares a value for the database, but doesn't send the prepared value back to the Python object in any way. For that you would need the pre_save method, I think.
Fortunately, there's already an "auto_now" option on DateField and DateTimeField that does what you want, using pre_save. Try:
class Table1(models.Model):
f = models.DateTimeField(auto_now=True)
(If you must write your own pre_save, look at how auto_now modifies the actual model instance in /django/db/models/fields/__init__.py on lines 486-492:
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = datetime.datetime.now()
setattr(model_instance, self.attname, value)
return value
else:
return super(DateField, self).pre_save(model_instance, add)
)