How to dynamically add domain in Odoo 8 - odoo-8

I work with Odoo 8 API v8 and I want to dynamically add a domain in a field.
I have 2 classes. A mother class purchase
TMP_BESOIN = {}
TMP_BESOIN['type']= ''
_name = 'purchase.besoin'
_description = "Expression du besion d'achat"
name = fields.Char(required=True,string="Reference",default='XXX',readonly=True)
employee_id = fields.Many2one('hr.employee', string="Demandeur", required=True)
date_expression_besoin = fields.Datetime(string="Date d'expression", required=True,default=fields.Datetime.now())
demandeprix_id = fields.Many2one('purchase.demandeprix.ligne', string='Demande de prix')
lignebesoin_ids = fields.One2many('purchase.besoin.ligne','besoin_id', string='Le besoin')
type = fields.Selection([('product', 'Produit stockable'), ('consu', 'Utilisation directe'), ('immo', 'Immobilisation')],
'Type d\'articles',defaut='product')
order_ids = fields.One2many('purchase.order','besoin_id', string='Le besoin')
destination = fields.Char(string='destination')
demandeprix_ids = fields.One2many('purchase.demandeprix','besoin_id', string='ligne demande de prix')
date_reject = fields.Datetime(string="Date de rejet", readonly=True)
user_reject = fields.Many2one('hr.employee', 'Rejété par', readonly=True)
date_validate = fields.Datetime(string="Date de Validation", readonly=True)
user_validate = fields.Many2one('hr.employee', 'validé par', readonly=True)
date_authorized = fields.Datetime(string="Date de d'autorisation", readonly=True)
user_authorized = fields.Many2one('hr.employee', 'autorisé par', readonly=True)
date_wait_authorisation = fields.Datetime(string="Date de transmition pour autorisation", readonly=True)
user_wait_authorisation = fields.Many2one('hr.employee', 'Transmit par', readonly=True)
date_done = fields.Datetime(string="Date de clôture", readonly=True)
user_done = fields.Many2one('hr.employee', 'clôturé par', readonly=True)
motivation = fields.Text('Designation')
state = fields.Selection([('draft', 'Brouillon'),
('reject', 'Besoin annulé'),
('validate', 'Besoin validé'),
('stock_verified', 'Stock vérifié'),
('wait_authorized', 'En attente d\'autorisation'),
('authorized', 'Autorisé')
], 'Etat',required=True,default='draft')
_sql_constraints = [
('ref_besoin_achat_uniq', 'unique(name)', 'La reference du besoin est unique'),
]
#api.model
def create(self,vals):
if not vals.has_key('name') or vals.get('name')=='XXX':
vals['name'] = self.env['ir.sequence'].get('purchase.besoin.achat.code') or 'XXX'
return super(purchase_besoin,self).create(vals)
#api.onchange('type')
def on_change_type(self):
global TMP_BESOIN
TMP_BESOIN = {}
TMP_BESOIN['type'] = self.type
This class defined global variable TMP_BESOIN and put value in method onchange_tye
this class is in relation many2one with another classe ligne_besoin
class purchase_besoin_ligne(models.Model):
_name = 'purchase.besoin.ligne'
_description = "Ligne du besoin d'achat"
name = fields.Char('Nom', readonly=True, store=True)
besoin_id = fields.Many2one('purchase.besoin', string='Besoin', required=True, ondelete='cascade')
besoin = TMP_BESOIN.copy()
produit_id = fields.Many2one('product.product', string="Article", required=True,domain=[('product_tmpl_id.type', 'like', besoin['type'])])
qte = fields.Integer(string="Quantité", required=True,default=1)
type = fields.Selection([('product', 'Produit stockable'), ('consu', 'Utilisation directe'), ('immo', 'Immobilisation')],
'Type d\'articles',defaut=besoin['type'])
Like as in my code, I want to add a domain in produit_id, in which the value of the domain, depends on the variable type in the Mother class.
As I cannot have the value of the variable besoin_id(link with the mother classes) before calling create method. I decided to use a global Variable
The problem is that, the filter doesn't apply without an error.

try the following: assuming that type is a column of product.product in the domain of produit_id.
_name = 'purchase.besoin.ligne'
_description = "Ligne du besoin d'achat"
name = fields.Char('Nom', readonly=True, store=True)
besoin_id = fields.Many2one('purchase.besoin', string='Besoin', required=True, ondelete='cascade')
besoin = TMP_BESOIN.copy()
produit_id = fields.Many2one('product.product', string="Article", required=True,domain=[('type', 'like', besoin_id.type])])
qte = fields.Integer(string="Quantité", required=True,default=1)
type = fields.Selection([('product', 'Produit stockable'), ('consu', 'Utilisation directe'), ('immo', 'Immobilisation')],'Type d\'articles',defaut=besoin['type'])

Related

Django TypeError get() argument after ** must be a mapping, not list

I'm creating a serializer for a model with a ManyToManyField (tag_id) that refers to a Tag table.
serializers.py
class CombinationSerializer(serializers.ModelSerializer):
# tag_id = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), source='tag', required=False, many=True)
tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Combination
depth = 1
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
score = 0
combination = Combination(
user=user,
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
created=datetime.now(),
score=score
)
combination.save()
tag_data = validated_data.pop('tag_id', None)
if tag_data:
tag = Tag.objects.get_or_create(**tag_data)[0]
validated_data['tag_id'] = tag
combination.tag_id.add(validated_data.get("tag_id"))
return combination
This is the problematic code:
tag_data = validated_data.pop('tag_id', None)
if tag_data:
tag = Tag.objects.get_or_create(**tag_data)[0]
validated_data['tag_id'] = tag
combination.tag_id.add(validated_data.get("tag_id"))
This is the JSON object I am trying to send in Postman:
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [{"id": 2001372884, "name": "combination", "language": "en"}]
}
What am I doing wrong here? Can this be done any other way?
The tag_id maps on a list of dictionaries, not a dictionary. You thus can enumerate over it:
tag_data = validated_data.pop('tag_id', None)
for tag_item in tag_data:
tag = Tag.objects.get_or_create(**tag_item)[0]
validated_data['tag_id'] = tag
since these are lists, it might be better however to make a list of tags in the validated data:
tag_data = validated_data.pop('tag_id', None)
validated_data['tag_id'] = [
Tag.objects.get_or_create(**tag_item)[0]
for tag_item in tag_data
]

Django REST update foreign key by id

Problem:
I want to update a foreign key field and I can not find my mistake why my changes to that fields are not saved. I want to be able to update clan and wingman.
serializer.py
class UpdateProfileInfoSerializer(serializers.Serializer):
id = serializers.CharField(required=True)
wingmanId = serializers.IntegerField(required=False)
clanId = serializers.IntegerField(required=False)
image = serializers.ImageField(required=False)
titleImage = serializers.ImageField(required=False)
description = serializers.CharField(required=False)
class Meta:
model = ProfileInfo
fields = ['id', 'clanId', 'description', 'image', 'titleImage', 'wingmanId']
def update(self, instance, validated_data):
clan_id = validated_data.get('clanId')
wingman_id = validated_data.get('wingmanId')
if clan_id:
if instance.clan:
instance.clan.id = clan_id
if wingman_id:
if instance.wingman:
instance.wingman.id = wingman_id
instance.image = validated_data.get('image', instance.image)
instance.titleImage = validated_data.get('titleImage', instance.titleImage)
instance.description = validated_data.get('description', instance.description)
instance.save()
return instance
Thank you for your help. I think I am doing something fundamentally wrong.
Try this please, I think it is better.
class UpdateProfileInfoSerializer(serializers.Serializer):
id = serializers.CharField(required=True)
wingmanId = serializers.IntegerField(required=False)
clanId = serializers.IntegerField(required=False)
image = serializers.ImageField(required=False)
titleImage = serializers.ImageField(required=False)
description = serializers.CharField(required=False)
class Meta:
model = ProfileInfo
fields = ['id', 'clanId', 'description', 'image', 'titleImage', 'wingmanId']
def update(self, instance, validated_data):
clan_id = validated_data.get('clanId')
wingman_id = validated_data.get('wingmanId')
if clan_id:
if instance.clan:
try:
clan_obj = Clan.objects.get(id=clan_id)
instance.clan = clan_obj
except:
pass
if wingman_id:
if instance.wingman:
try:
wingman_obj = Wingman.objects.get(id=wingman_id)
instance.wingman = wingman_obj
except:
pass
instance.image = validated_data.get('image', instance.image)
instance.titleImage = validated_data.get('titleImage', instance.titleImage)
instance.description = validated_data.get('description', instance.description)
instance.save()
return instance

odoo one2many list remove duplicates items

i have developed a module of purchase in odoo 10 community when i make a cammand of products i want to disable duplicate choose of product in widget one2many list as in the image below:
enter image description here
i want to prevent duplicate entry in the products list here is the code of my command module:
class PalBl(models.Model):
_name = 'pal.bl'
name = fields.Char('Reference', required=True)
supplier = fields.Many2one('pal.vendor', required=True)
date = fields.Date('Date', required=True)
totalHt = fields.Float('Total HT', store=True, readonly=True, compute='_get_tot')
totalTtc = fields.Float('Total TTC', store=True, readonly=True, compute='_get_tot')
items_id = fields.One2many('pal.prs.com', 'prod_id')
dateliv = fields.Date('Date de livraison prévue')
nb_pr = fields.Integer('Total de Produit')
state = fields.Selection([(1, 'En attente'), (2, 'Reglée')], 'type', default=1)
_sql_constraints = [('item_code_uniq', 'unique(items_id.name.code)', "le code d'un produit doit etre unique !")]
and this the code of the products:
class PalPrcom(models.Model):
_name = 'pal.prs.com'
name = fields.Many2one('pal.stock', 'Désignation', required=True)
code = fields.Char('Ref produit', store=True, readonly=True, compute='_getref', inverse='_gedef')
quantity = fields.Integer('Quantité', required=True, default=1)
price = fields.Float('Prix achat HT', store=True, readonly=True, compute='_getref')
tva = fields.Integer('TVA')
remise = fields.Integer('Remise')
prod_id = fields.Many2one('pal.bl')
_sql_constraints = [ ('quantity_gt_zero', 'CHECK (quantity>0)', 'La quantité de produit doit etre supérieur à zéro!')
]
You can use two for loops which will iterate over your one2many field and check for duplicates
This will work.
_sql_constraints = [('order_name', 'unique (relation_id,field_name_1,field_name_2)',
'Duplicates are not allowed!')]

Convert Suport Ticket to TASK Odoo 9

Is it possible convert Suport Ticket to Project > Task.
Task Title = Suport subject, Task Description = Suport Description...
Example:
I use this modul https://www.odoo.com/apps/modules/9.0/website_support/
In support ticket i want add:
Below is new function def generate_task(self): how generate new TASK from that.
class WebsiteSupportTicketCompose(models.Model):
_name = "website.support.ticket.compose"
ticket_id = fields.Many2one('website.support.ticket', string='Ticket ID')
partner_id = fields.Many2one('res.partner', string="Partner", readonly="True")
email = fields.Char(string="Email", readonly="True")
subject = fields.Char(string="Subject", readonly="True")
body = fields.Html(string="Message Body")
template_id = fields.Many2one('mail.template', string="Mail Template", domain="[('model_id','=','website.support.ticket')]")
#api.onchange('template_id')
def _onchange_template_id(self):
if self.template_id:
values = self.env['mail.compose.message'].generate_email_for_composer(self.template_id.id, [self.ticket_id.id])[self.ticket_id.id]
self.body = values['body']
#api.one
def send_reply(self):
#Send email
values = {}
email_wrapper = self.env['ir.model.data'].get_object('website_support','support_ticket_reply_wrapper')
values = email_wrapper.generate_email([self.id])[self.id]
values['model'] = "website.support.ticket"
values['res_id'] = self.ticket_id.id
send_mail = self.env['mail.mail'].create(values)
send_mail.send()
#(Depreciated) Add to message history field for back compatablity
self.env['website.support.ticket.message'].create({'ticket_id': self.ticket_id.id, 'content':self.body.replace("<p>","").replace("</p>","")})
#Post in message history
#self.ticket_id.message_post(body=self.body, subject=self.subject, message_type='comment', subtype='mt_comment')
staff_replied = self.env['ir.model.data'].get_object('website_support','website_ticket_state_staff_replied')
self.ticket_id.state = staff_replied.id
#api.one
def generate_task(self):
values = {}
print(self.ticket_id.id)
print(self.email)
print(self.subject)
print(self.body.replace("<p>","").replace("</p>",""))
#How this data insert in new TASK
Any simple solution?
Try below code:
#api.multi
def generate_task(self,cr, uid, ids, context=None):
Task = self.pool["project.task"]
vals = {
"name": "TEST",
"description": "DESCRIPTION",
}
task_id = Task.create(cr,uid,vals,context=None)
task = Task.browse(cr,uid,task_id,context=None)

Database migration with Entity Framework

I have strange result in database (SQL Server 2008)-.
I work on a ASP.NET MVC 3 project with Entity Framework, and I use database migrations.
When I modify the schema of my database, and in configuration file (Configuration.cs) seed method, I have the following code to initialize data after any migration :
protected override void Seed(YAnnonce.Core.Repository.AnnonceDbContext context)
{
var categorieAnnonces = new List<CategorieAnnonce>
{
new CategorieAnnonce{ CategorieAnnonceID = 1, CategorieName="Emploi"},
new CategorieAnnonce{ CategorieAnnonceID = 2, CategorieName="Stage"},
};
categorieAnnonces.ForEach(a => context.CategorieAnnonces.AddOrUpdate(a));
context.Annonces.AddOrUpdate(new Annonce[10]{
new Annonce {AnnonceID=250, titre = "Offre d'emploi", CategorieAnnonce = categorieAnnonces[0], description="le cabinet de recrutement le pole offre à toute pe",date=DateTime.Now,etat=1, mode = 0, EndDate = DateTime.Now},
new Annonce {AnnonceID=490, titre = "Formation", CategorieAnnonce = categorieAnnonces[1], description="Le cabinet de recrutement et de formation maroc ",date=DateTime.Now,etat=0, mode = 1, EndDate = DateTime.Now},
new Annonce {AnnonceID=380,titre = "Freelance", CategorieAnnonce =categorieAnnonces[1], description="Bonjour, jeune développeur en informatique vous assurant ",date=DateTime.Now, etat=1, mode = 1, EndDate = DateTime.Now});
}
but the problem is that the same data is added to the database after any migration, and I don't want this scenario.
You must determine in which state database migration should be used.There are different ways to do this, and i suggest one of them. Write a class like this and put Seed function into it :
public class DataContextInitializer:DropCreateDatabaseIfModelChanges<YAnnonce.Core.Repository.AnnonceDbContext>
{
var categorieAnnonces = new List<CategorieAnnonce>
{
new CategorieAnnonce{ CategorieAnnonceID = 1, CategorieName="Emploi"},
new CategorieAnnonce{ CategorieAnnonceID = 2, CategorieName="Stage"},
};
categorieAnnonces.ForEach(a => context.CategorieAnnonces.AddOrUpdate(a));
context.Annonces.AddOrUpdate(new Annonce[10]{
new Annonce {AnnonceID=250, titre = "Offre d'emploi", CategorieAnnonce = categorieAnnonces[0], description="le cabinet de recrutement le pole offre à toute pe",date=DateTime.Now,etat=1, mode = 0, EndDate = DateTime.Now},
new Annonce {AnnonceID=490, titre = "Formation", CategorieAnnonce = categorieAnnonces[1], description="Le cabinet de recrutement et de formation maroc ",date=DateTime.Now,etat=0, mode = 1, EndDate = DateTime.Now},
new Annonce {AnnonceID=380,titre = "Freelance", CategorieAnnonce =categorieAnnonces[1], description="Bonjour, jeune développeur en informatique vous assurant ",date=DateTime.Now, etat=1, mode = 1, EndDate = DateTime.Now});
}
and then in your main/root web.config file, add below key to run the above class during the application run:
<appSettings>
<add key="DatabaseInitializerForType YAnnonce.Core.Repository.AnnonceDbContext, [Project_Name]" value="DataContextInitializer, [Project_Name]" />
</appSettings>
Check whether the records exists before inserting.
If you consider the data to be inserted in a single transaction, then you can search if any one of the records exists before inserting.
i.e
if(!context.Annonces.Any(x=>x.AnnonceID==250)){ //insert records here }

Resources