I get this error and I don't know how to solve it:
My code:
#api.constrains('num_dossier')
def identify_same_num(self):
for record in self:
obj = self.search([('num_dossier','=',record.num_dossier),('arrondissement_id','=',record.arrondissement_id.id)])
if obj:
raise except_orm('Erreur')
For the database :
_sql_constraints = [
('number_uniq', 'unique(number, company_id, journal_id, type)','Numéro de facture doit etre unique par company!'),
('num_dossier_uniq', 'unique(num_dossier,arrondissement_id)', 'Numéro de dossier doit etre unique par Arrondissement')
]
Related
I' m creating a fastapi API usinging tortoise-orm and sqlite and the bloblem that i have is that in one of my models witch is "Member", i wanna have a possibility for the member to put their phone number with their country code bu i dont'n kwow how to handle that; I'm using "phon_num= fields.CharField(max_length=13)", I wonder how am I gonna allow only numbers to be put in that fields. tanks
#app.post("/members")
async def create_member(name:str, email:EmailStr, phon_num:str,adress:str):
member = await Member.create(name=name, email=email,phon_num=phon_num, adress=adress)
if member.phon_num.isnumeric:
member.save()
return member
else:
return {"status": "vous avez un probleme dans le remplissage de votre formulaire",
"detail": "votre numero ne doit contenir que des chiffre ansi que l'indicatif pay '+code pays', avant d'entrer le numero"}
I expected that the if statement could control either the input is a string witch contains only the number and verify if in that string there is a "+" character for the country code.
I want to transfer the value of a field days_compensation to another field days_compensation_remaining but which are not in the same models and field 2 has attibutes compute and inverse, I am blocked there, thank you in advance(it's a challenge for everyone haha)
My code :
In this model (hr.employee) :
Classe and field :
class HrEmployee(models.Model):
_inherit = 'hr.employee'
days_compensation_remaining = fields.Float(
'Jours de récupération restant',
compute='_compute_days_compensation_remaining',
readonly=True,
inverse='_inverse_days_compensation_remaining',
help='Nombre total des jours de récupération ',
)
Inverse methode :
#api.multi
def _inverse_days_compensation_remaining(self):
self.ensure_one()
compensation_legal_leave = self.company_id.days_compensation_holidays_status_id
if not compensation_legal_leave:
raise UserError(_("le type de congé pour les jours de récupération n'est pas défini"))
diff = self.days_compensation_remaining - compensation_legal_leave.get_days(
self.id)[compensation_legal_leave.id].get('days_compensation_remaining', 0.0)
if diff > 0:
leave = self.env['hr.holidays'].create(
{
'name': 'Allocation for %s' % self.name,
'employee_id': self.id,
'holiday_status_id': compensation_legal_leave.id,
'type': 'add',
'holiday_type': 'employee',
'number_of_days_temp': diff
}
)
leave.action_approve()
if leave.double_validation:
leave.action_validate()
elif diff < 0:
raise UserError(_('vous ne pouvez pas réduire le nombre de jours'))
Compute methode :
#api.multi
def _compute_days_compensation_remaining(self):
for r in self:
compensation_legal_leave = r.company_id.days_compensation_holidays_status_id
if not compensation_legal_leave:
raise UserError(_("le type de congé pour les jours de récupération n'est pas défini"))
r.days_compensation_remaining = compensation_legal_leave.get_days(
r.id)[compensation_legal_leave.id].get('days_compensation_remaining', 0.0)
In this Model (hr.employee.mission) :
class HrMission(models.Model):
_inherit = "hr.employee.mission"
days_compensation =fields.Float(compute='get_compensation', string='Jours de récupération', help="Jours de récupération si la mission contient les jours de repos",
required=True, readonly=True, store=True)
#api.multi
#api.depends("mission_start_date", "mission_end_date")
def get_compensation(self):
for rec in self:
if rec.mission_start_date and rec.mission_end_date:
date_start = datetime.strptime(rec.mission_start_date,"%Y-%m-%d").date()
date_end = datetime.strptime(rec.mission_end_date,"%Y-%m-%d").date()
delta_day = timedelta(days=1)
days = {'mon':0,'tue':1,'wed':2,'thu':3,'fri':4,'sat':5,'sun':6}
dt = date_start
fri_count = 0
while dt <= date_end:
if dt.weekday() == days['fri']:
fri_count+=1
dt += delta_day
rec.days_compensation = fri_count
I don't understand why here it works :
# Fonction qui récupère la valeur du champs booléen inscription de l'année précédente
#api.depends('half_pension')
def _retrieve_halfpension_previous(self):
records = self.env['ecole.partner.school'].search([])
for record in records:
record.half_pension_previous = record.half_pension
And here, i have a error expected singleton:
# Fonction qui récupère la valeur du champs booléen inscription de l'année précédente
#api.depends('half_pension')
def _retrieve_halfpension_previous(self):
records = self.env['ecole.partner.school'].search([('id', '<', self.id)])
for record in records:
record.half_pension_previous = record.half_pension
Why ?
Thanks You
The error is because you are using self.id where self is a recordset containing more than one value. Normally to solve it you need to iterate the recordset in self to access every record field like this:
#api.depends('half_pension')
def _retrieve_halfpension_previous(self):
for rec in self:
records = self.env['ecole.partner.school'].search([('id', '<', rec.id)])
for record in records:
record.half_pension_previous = record.half_pension
But in this case it will be ok to find the max id of the records in self to use it in just one search, like:
#api.depends('half_pension')
def _retrieve_halfpension_previous(self):
max_id = max([rec.id for rec in self])
records = self.env['ecole.partner.school'].search([('id', '<', max_id)])
for record in records:
record.half_pension_previous = record.half_pension
I having a lot of problem with something I'm sure is pretty easy, but not for me.
I have 2 Models:
VipPassesModel
ProfileModel
Then I've this view, wich purpose is perform the following task (in this order):
Search if the "VIP Code" exists in the "VipPassesModel"
If "VIP Code" exists check if as some User (Profile Model - Foreing Key) asigned to it
If there's no user asigned to that VIP Code, then SAVE the current User logued (Id - Foreign Key) in that VIP Code (this will make this Vip Code no longer available)
My VipPassesModel:
class VipPassesModel(models.Model):
"""
VIP Passes Code Model.
"""
code = models.CharField(max_length = 15)
is_used = models.BooleanField(default=False)
user_asigned = models.ForeignKey(ProfileModel, related_name='profile_name', verbose_name="User Full Name", blank=True, null=True,)
My View.py
def vipcodevalidation(request):
"""
Funcion que recibe el CODE VIP y si es valido, lo asigna al usuario actual
"""
if request.method == 'POST':
form = VipPassesForm(data=request.POST)
if form.is_valid():
vipcode = form.cleaned_data['code']
user_to_asign = request.user
if VipPassesModel.objects.filter(code = vipcode).exists():
# Tomar el objeto y grabarle en "user_asigned" el id del usuario de django logueado actualmente (user_to_asign)
else:
#nada que hacer aqui
else:
form = VipPassesForm()
return render(request,'vipcode.html',{'form':form},context_instance=RequestContext(request))
I'll apreciate any help from you guys. Just to be clear, I'm not getting error messages, just I don't know how to deal with this.
Your view should be:
if VipPassesModel.objects.filter(code = vipcode): #If there is object with that code
vipObject = VipPassesModel.objects.filter(code = vipcode)[0] # Get the object
if not vipObject.user_assigned: #If object doesn't have user
vipObject.user_assigned = request.user.id # Assign actual user
vipObject.save() # Save object
else:
#nada que hacer aqui
When you do if VipPassesModel.objects.filter(code = vipcode): if there is no objects, you get [](empty list) so, if you do if [] it returns false, because the list is empty, if there is one model with tat code, it returns the object like [VipPassesModel] so to access to it you need to do VipPassesModel.objects.filter(code = vipcode)[0]
(la documentación de Django oficial sobre este tipo de querys está bastante bien, te recomiendo que le eches un ojo a Django Queries )
THANK YOU SO MUCH GUYS!... You're the best... I need more friends like you.
This is the final View Code:
def vipcodevalidation(request):
"""
Funcion que recibe el CODE VIP y si es valido, lo asigna al usuario actual
"""
if request.method == 'POST':
form = VipPassesForm(data=request.POST)
if form.is_valid():
vipcode = form.cleaned_data['code']
user_to_asign = request.user.id
if VipPassesModel.objects.filter(code = vipcode):
vipObject = VipPassesModel.objects.filter(code = vipcode)[0] # Get the object
if not vipObject.user_asigned: #If object doesn't have user
vipObject.user_asigned = ProfileModel.objects.get(pk = user_to_asign) # Assign actual user
vipObject.save() # Save object
# VIP Code encontrado y User Asignado.
else:
# VIP Code encontrado pero ya tiene un User Asignado.
else:
#VIP Code no encontrado o ya tiene un User Asignado
else:
form = VipPassesForm()
return render(request,'vipcode.html',{'form':form},context_instance=RequestContext(request))
Simplistically this is what you can do
try:
vipobj = VipPassesModel.objects.filter(code = vipcode, user_asigned = NULL)[0]
except IndexError:
#no vip code free to assign bail out
vipobj.user_assigned = user_to_asign
vipobj.save()
In real production level code, you should make these in a transaction sol that 2 requests from different user does not clash. 2nd request may override assignment by 1st request.
For logs parsing, I need to remove a pattern in a log file:
Pattern:
Acces : Lecture donnees (ou liste de repertoire) Privileges : - Nombre de SID restreint : 0 Masque d acces : 0x1 "
Log sample:
# This line has to be kept
2014-03-03 09:50:20,2014-03-03 09:50:20,560,Success Audit event,Accès aux objets,Security,LA\USER1,LA-SERVER1,"Objet ouvert : Serveur de l’objet : Security Type d’objet : File Objet : \vol\vol01\PROD\prod.conf Identificateur du handle : 554 Identificateur de l’opération : - ID du processus : 2050 Nom du fichier image : Server Soft Utilisateur principal : user1 Domaine principal : LA ID d’ouv. de session principale : (0x0, 0x9596) Utilisateur client : 1.2.3.4 Domaine client : - ID d’ouv. de session client : - Acces : Lecture données (ou liste de répertoire) Écriture données (ou ajout fichier) Ajout données (ou ajout sous-répertoire ou créer instance de canal) WRITE_DAC Privilèges : - Nombre de SID restreint : 0 Masque d’accès : 0x40007 "
# This line has to be removed
2014-03-03 09:52:20,2014-03-03 09:50:20,560,Success Audit event,Accès aux objets,Security,LA\USER2,LA-SERVER1,"Objet ouvert : Serveur de l’objet : Security Type d’objet : File Objet : \vol\vol01\PROD\prod.conf Identificateur du handle : 554 Identificateur de l’opération : - ID du processus : 2050 Nom du fichier image : Server Soft Utilisateur principal : user1 Domaine principal : LA ID d’ouv. de session principale : (0x0, 0x9597) Utilisateur client : 1.2.3.5 Domaine client : - ID d’ouv. de session client : - **Acces : Lecture donnees (ou liste de repertoire) Privileges : - Nombre de SID restreint : 0 Masque d acces : 0x1 "**
# This line has to be removed
2014-03-03 09:53:20,2014-03-03 09:50:20,560,Success Audit event,Accès aux objets,Security,LA\USER3,LA-SERVER1,"Objet ouvert : Serveur de l’objet : Security Type d’objet : File Objet : \vol\vol01\PROD\prod.conf Identificateur du handle : 554 Identificateur de l’opération : - ID du processus : 2050 Nom du fichier image : Server Soft Utilisateur principal : user1 Domaine principal : LA ID d’ouv. de session principale : (0x0, 0x9597) Utilisateur client : 1.2.3.6 Domaine client : - ID d’ouv. de session client : - **Acces : Lecture donnees (ou liste de repertoire) Privileges : - Nombre de SID restreint : 0 Masque d acces : 0x1 "**
I found a script here (thx to ATOzTOA) to do the job (I just added sys module):
import sys
fname = sys.argv[1]
def delete_line(dello):
data = open(fname).readlines()
i = 0
for line in data:
if dello in line:
data.pop(i)
i += 1
open(fname, "w").write("".join(data))
delete_line("Acces : Lecture donnees (ou liste de repertoire) Privileges : - Nombre de SID restreint : 0 Masque d acces : 0x1\"")
When I run the script, it didn't remove the 2 lines of logs which contain the pattern : only one of the two.
I have to run once or twice again the script to delete all the lines
I don't know why.
You shouldn't increment i when calling pop(). Also, you shouldn't use pop() when iterating over a list. This is because if you remove an element from the middle of a list, then you skip some items while iterating.
You should rewrite delete_line() as follows:
def delete_line(dello):
with open(fname) as f:
data = [line for line in f if dello not in line]
with open(fname, 'w') as f:
f.write(''.join(data))
(Note that there is room for improvement.)
An another problem is that you are giving delete_line() the wrong argument: there's a space between 0x1 and ". This is the correct line:
delete_line('Acces : Lecture donnees (ou liste de repertoire) Privileges : - Nombre de SID restreint : 0 Masque d acces : 0x1 "')
By the way, there's already an excellent program that filters out lines from a file: it's grep (with the -v option).
I can't replicate your error locally. However, I will suggest that you can try the python replace method instead.
http://www.tutorialspoint.com/python/string_replace.htm
str.replace(old, new[, max])
which will search for the replaced it with what you want in your string.
Therefore, the one possible solution to your problem will be :
import sys
fname = sys.argv[1]
def delete_line(dello):
cleaned_data = []
data = open(fname).readlines()
for line in data:
line = line.replace(dello, "")
cleaned_data.append(line)
open(fname, "w").write("".join(data))
delete_line("Acces : Lecture donnees (ou liste de repertoire) Privileges : - Nombre de SID restreint : 0 Masque d acces : 0x1\"")
You may replace your for loop with a list comprehension
clean_data = [line.replace(dello,"") for line in data]