I've got this function
def add_default_docs(self):
for r in self:
id = self.id
labs_archive_journal_type_id = r.journal_type_id.id
archive_doc_name_ids = self.env['labs.archive.journal_type'].search([('id', '=', labs_archive_journal_type_id)]).archive_doc_name_ids
for n in archive_doc_name_ids:
self.env['labs.archive.document'].create({
"archive_journal_id": id,
"name": n.id
})
How could I call it when I press 'Create' button and create new record?
Whichever model you want to fire this function on creation on new model, inherit that model if that model is odoo built-in or if your own model, within that model definition inherit create method as following:
class ClassName(models.Model)
_inherit = 'model.name'
#api.multi
def create(self, vals):
records = super(ClassName, self).create(vals)
records.add_default_docs()
return records
If your model is defined in your own custom module, you can just insert this create function within that model definition, you won't need to inherit in new class.
Related
On odoo 8.0 I need to override parent model init() method, but the new init() is never called upon upgrading the module
Is there some obscure undocumented odoo trick for this?
class A(models.Model):
_name = "A"
_auto = False
columnA = ....
def init(self, cr):
# ... here there is a CREATE VIEW ....
# in another module...
class A(models.Model)
_inherit = "A"
_auto = False
columnB = ....
def init(self, cr):
#... NEW VIEW DEFINITION ...
Upon upgrading the module, inherited init() never gets called.
It always calls parent (class A) init method.
Amazingly, columnB is created in the modelA, hence inherited class is considered.... but at run time, its init() method is not called*
Verified in debug mode and with breakpoints set
I don't know how to disable sending email invitation when i create or import user.
I tried to override auth_signup module with this code but i have a recursion error: Unknown error during import: : maximum recursion depth exceeded at row 2
And the code :
class res_users(models.Model):
_inherit = 'res.users'
#api.model
def create(self, vals):
user = super(res_users, self).with_context(no_reset_password=True).create(vals)
return user
with_context will cause a recursion error when applied with super. super calls the base class, which is not what you need. What you need is to update the context of the current instance of the class, which is self.
Therefore this should work:
class res_users(models.Model):
_inherit = 'res.users'
#api.model
def create(self, vals):
user = super(res_users, self.with_context(no_reset_password=True)).create(vals)
return user
In a custom module I have two classes. How can class test in #api.one call test2_func on a button click?
What should I put in def call_test2_func(self)?
For example:
class test(models.Model):
_name = "test.class"
_description = "TEST"
#api.one
def call_test2_func(self):
"""call test2_func here"""
class test2(models.Model):
_name = "test2.class"
_description = "TEST 2"
#api.one
def test2_func(self):
print("TEST 2")
Maybe I should leave a reply instead of a comment. If you're using Odoo and the new OpenERP api you can can access the model dictionaty though self.env in your model classes. So to call the function test2_func in the model test2.class you should write
#api.one
def call_test2_func(self):
self.env["test2.class"].test2_func()
I'm having some trouble to understand how to get field values from another model.
I added a custom field in res.partner module by making a custom module:
class custom_partner_fields(osv.osv):
_inherit = 'res.partner'
_columns = {
'RTN': fields.char('RTN Numerico'),
}
_defaults = {
}
custom_partner_fields()
Then I create a custom xml for the form view when creating a new customer and now I can see RTN field in the customer create form.
Now I want this new field to appear when making a new quotation/sale order.
I would like it to get its value when I select my customer (I believe onchange function should be use but don't know how to use that!),so what I did was create a custom module for it:
class custom_saleorder_fields(osv.osv):
_inherits = 'sale.order'
_columns = {
'partner_rtn': fields.char('RTN'),
}
custom_saleorder_fields()
I believe I need to use something like a function or relational field for this but what I've tried hasn't worked yet.
Then, I created the custom view form the sale order form view and adds my partner_field.
Now, I would like to know how can I access the specific RTN value from res.partner module from custom_saleorder_fields based on the selected customer.
On the other hand, the main purpose of this new value is to displayed in the sale workflow and also print it in a report.
You need to add relational field in sale order model.
Before applying code you should refer that documentation of odoo,
In the Odoo Field Doc you will know how fields.related works.
class custom_saleorder_fields(osv.osv):
_inherits = 'sale.order'
_columns = {
'partner_rtn': fields.related('partner_id','RTN',type="char",relation="res.partner",string="RTN",store=True,readonly=True),
}
custom_saleorder_fields()
bring modelA fields in modelB by relatiional fields
eg use many2one field in another model :
from openerp import models, fields, api
class partsproviderclass(models.Model):
_name='partsprovider.vechicle'
#_rec_name='parts_provider'
id=fields.Integer()
parts_provider=fields.Many2many('supplier.car', string="Parts provider")
parts_name=fields.Many2many('selection.selection',string="Parts Name")
parts_price=fields.Float(string="Price of the Part")
class selectionsxample(models.Model):
_name='selection.selection'
name=fields.Char('name',required=True)
value=fields.Char('value',required=True)
I would like to have a nested object inside a serializer instead of just the foreignkey (or url).
As this documentation says, I just had to specify the serializer class of the nested object in the parent serializer:
# Models
class NestedSample(models.Model):
something = models.CharField(max_length=255)
class Sample(models.Model):
thing = models.BooleanField()
nested = models.ForeignKey(NestedSample)
# Serializers
class NestedSampleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = api_models.NestedSample
class SampleSerializer(serializers.HyperlinkedModelSerializer):
nested = NestedSampleSerializer() # HERE!
class Meta:
model = api_models.Sample
# Views
class NestedSampleViewSet(viewsets.ModelViewSet):
queryset = api_models.NestedSample.objects.all()
serializer_class = api_serializers.NestedSampleSerializer
class SampleViewSet(viewsets.ModelViewSet):
queryset = api_models.Sample.objects.all()
serializer_class = api_serializers.SampleSerializer
This works very well when I get the objects, but it is not possible to create (=POST) Sample objects anymore, I get the error:
{u'non_field_errors': [u'Invalid data']}
I tried to overwrite the create method in the viewset to get the object using the pk:
class SampleViewSet(viewsets.ModelViewSet):
queryset = api_models.Sample.objects.all()
serializer_class = api_serializers.SampleSerializer
def create(self, request):
request.DATA['nested'] = get_object_or_404(api_models.NestedSample, pk=request.DATA['nested'])
return super(SampleViewSet, self).create(request)
But it doesn't work as well.
Any idea?
I also found this question I can relate with which of course solves the problem but do not let me expose the full nested object, so back to the beginning.
Thanks,
I can think of two solutions to this problem. I prefer the first one.
First solution:
Use a django model form to create objects. Override the create and update methods. A sample create method:
def create(self, request):
form = SampleForm(data=request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return Response(dict(id=instance.pk), status=status.HTTP_201_CREATED)
return Response(form.errors, status=status.HTTP_400_BAD_REQUEST)
this way you can create Sample objects with any kind of validation you like.
Second solution:
Override get_serializer_class method and return serializer class based on request method. Define two serializers one for post and put and one for list and retrieve.
Can you confirm that you're sending a JSON encoded request - i.e. the request has the content type set to JSON ?
If not, the post is most probably send using form format which doesn't support nested.