Odoo 11 one2many field not saving - python-2.7

In Odoo v10 this on_change method worked pretty well:
#api.onchange("partner_id")
def onchange_partner_id(self):
self.zapocet_line_pohledavky = False
self.zapocet_line_zavazky = False
account_move_line_obj = self.env['account.move.line']
val = {'value': {'zapocet_line_pohledavky': [], 'zapocet_line_zavazky': []}}
for statement in self:
if statement.partner_id:
domain = [('account_id.user_type_id.type', 'in', ('payable', 'receivable')), ('move_id.state', '=', 'posted'),
('partner_id.id', '=', statement.partner_id.id),]
line_ids = account_move_line_obj.search(domain, order="date asc")
for line in line_ids:
if line.amount_residual != 0 and line.credit > 0:
res = {
"move_line_id": line.id,
}
val['value']['zapocet_line_zavazky'].append(res)
if line.amount_residual != 0 and line.debit > 0:
qes = {
"move_line_id": line.id,
}
val['value']['zapocet_line_pohledavky'].append(qes)
self.zapocet_line_pohledavky = val['value']['zapocet_line_pohledavky']
return val
Does anybody have a clue why in v11 it loads the lines well, but they disappear on saving?

Related

I need to test django filters applying different lookup_expr on the same field

I have a challenge model with fields: name, start_date and end_date. I need to apply different django filters to each field like this
class ChallengeFilter(filters.FilterSet):
class Meta:
model = Challenge
fields = {
"name": ["exact", "icontains"],
"start_date": ["exact", "lte", "gte"],
"end_date": ["exact", "lte", "gte"],
}
when I test the exact lookup_expr it works okay but I need help testing "icontains" or "lte" or "gte"
Here's my test for exact
def test_challenge_filter_by_name(self, user):
c1 = ChallengeFactory(name="chal", owner=user)
c2 = ChallengeFactory(name="star", owner=user)
data = {
"name": "chal",
}
challenge_filter = ChallengeFilter(data, queryset=Challenge.objects.all())
assert challenge_filter.is_valid()
assert challenge_filter.qs.count() == 1
and here's the test I tried with contains but if fails assert 0 == 1
def test_challenge_filter_by_name_contains(self, user):
c1 = ChallengeFactory(name="chal", owner=user)
c2 = ChallengeFactory(name="star", owner=user)
data = {
"name": "challenge",
}
challenge_filter = ChallengeFilter(data, queryset=Challenge.objects.all())
assert challenge_filter.is_valid()
assert challenge_filter.qs.count() == 1
I also don't know how to test gte and lte for dates.
You are trying to check if "challenge" is contained in either "chal" or "star". You should name one Challange "challenge" and then filter by "chal".
c1 = ChallengeFactory(name="challange", owner=user)
c2 = ChallengeFactory(name="star", owner=user)
data = {
"name": "chall",
}
challenge_filter = ChallengeFilter(data, queryset=Challenge.objects.all())
assert challenge_filter.is_valid()
assert challenge_filter.qs.count() == 1

How to save a table from Datatables to a database in Django?

I'm using Datatables to display tables in Django on the server side. After searching for a phrase, I have a button ready to save the current table after filtering to Excel. I would like the second button to create a new table in the database and save the same table to it as for Excel.
I don't know how I can send AJAX data to Django and read it in views in such a way that I can query the database.
javascript:
$(document).ready(function () {
function newexportaction(e, dt, button, config) {
var self = this;
var oldStart = dt.settings()[0]._iDisplayStart;
dt.one('preXhr', function (e, s, data) {
data.start = 0;
data.length = 2147483647;
dt.one('preDraw', function (e, settings) {
// Call the original action function
if (button[0].className.indexOf('buttons-excel') >= 0) {
$.fn.dataTable.ext.buttons.excelHtml5.available(dt, config) ?
$.fn.dataTable.ext.buttons.excelHtml5.action.call(self, e, dt, button, config) :
$.fn.dataTable.ext.buttons.excelFlash.action.call(self, e, dt, button, config);
}
dt.one('preXhr', function (e, s, data) {
settings._iDisplayStart = oldStart;
data.start = oldStart;
});
});
});
dt.ajax.reload();
}
$("#tb").DataTable({
"lengthChange": true,
"paging": true,
"searching": true,
"oLanguage": {
"sSearch": "Szukaj:",
},
"language": {
"processing": "Przetwarzanie",
"lengthMenu": "Pokaż _MENU_ elementów",
"info": "Wyświetlono od _START_ do _END_ z _TOTAL_ elementów",
"zeroRecords": "Nie znaleziono pasujących elementów",
"paginate": {
"first": "Pierwsza",
"last": "Ostatnia",
"next": "Kolejna",
"previous": "Poprzednia"
},
"emptyTable": "Brak danych do wyświetlenia",
},
"processing": true,
"serverSide": true,
buttons: [
{
extend: 'excel',
titleAttr: 'Excel',
title: '',
action: newexportaction
},
],
dom: 'B<"clear">lfrtip',
// "destroy": true,
"pageLength": 15,
"ordering": false,
"ajax": {
"url": "paging2/",
"type": "get"
},
});
});
views.py:
def paging2(request):
draw = int (request.GET.get ('draw')) # record the number of operations
start = int (request.GET.get ('start')) # start position
length = int (request.GET.get ('length')) # length of each page
search_key = request.GET.get ('search[value]') # search keyword
order_column = request.GET.get ('order [0] [column]') # sort field index
order_column = request.GET.get ('order [0] [dir]') #Ordering rule: ase / desc
# sql query all data, then do paging, the speed is slow
# if search_key:
# result = query(search_key)
# else:
# result = select_all()
# data = result[start:start+length]
# count = len(result)
# sql for paging, fast
if search_key:
sql_search = "SELECT NAZWA,TEL,NIP,Adres,WWW, EMAIL, Branza, NAZWA_SCRAPERA FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL AND Branza like '%%%s%%'" % search_key
sql_search_len = "SELECT COUNT(*) FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL AND Branza like '%%%s%%'"% search_key
result, count = query(sql_search, sql_search_len)
data = result[start:start + length]
else:
sql = """
SELECT NAZWA,TEL,NIP,Adres,WWW, EMAIL, Branza, NAZWA_SCRAPERA FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL
LIMIT %s OFFSET %s
"""
data = select_by_page(length, start, sql)
# data = select_by_page(start, start + length)
sql_len = "SELECT COUNT(*) FROM gus_all t1 WHERE NOT EXISTS (SELECT * FROM matka_new t2 WHERE t2.NIP = t1.NIP) AND LENGTH(TEL) = 9 AND `STATUS` = 'AKTYWNY' AND NAZWA_SCRAPERA is NOT NULL"
count = all_count(sql_len)
dic = {
'draw': draw,
'recordsTotal': count,
'recordsFiltered': count,
'data': data,
}
return HttpResponse(json.dumps(dic), content_type='application/json')

Unable to create a record in except loop of try-except odoo10

When i call the below function through API;
In both try and except conditions I have to keep log in separate table named api.log.
While the function enters in except condition, error occurs on creating record on api.log table
Here is the code:
#http.route('/tax_master',type="json",methodn ['POST'],auth="public",csrf=Falenter code herese)
def create_tax_master(self,**kw):
kw = http.request.params
obj_tax_master = request.env['tax.master']
obj_account_tax = request.env['account.tax']
flag = kw.get('flag')
vals = {}
result = False
if kw.get('name'):
vals['name'] = kw.get('name')
if kw.get('value'):
vals['value'] = kw.get('value')
if kw.get('scope'):
vals['scope'] = kw.get('scope')
if kw.get('is_excise'):
vals['is_excise'] = kw.get('is_excise')
if kw.get('description'):
vals['description'] = kw.get('description')
if kw.get('amount_type'):
vals['amount_type']= kw.get('amount_type')
if 'is_excise' in kw and kw.get('is_excise') not in [1,0]:
result = json.dumps({
"statusCode":02,
"statusDesc":"The value for the field is_excise should be 0 or 1"})
try:
if flag == 'create':
tax_id = obj_tax_master.sudo().create(vals).id
result = json.dumps({"id":tax_id,
"statusCode":01,
"statusDesc":"Successfully Created"
})
elif flag == 'write':
if kw.get('id'):
tax_id_rec = obj_tax_master.sudo().browse([int(kw.get('id'))])
if tax_id_rec.active == False:
result = json.dumps({
'statusCode': 02,
'statusDesc': 'The Tax is Archived.Updation is not possible now',
})
else:
tax_id_rec.sudo().write(vals)
tax_id = kw.get('id')
result = json.dumps({"id":tax_id,
"statusCode":01,
"statusDesc":"Successfully Updated"
})
else:
result = json.dumps({
'statusCode' : 02,
'statusDesc' : 'Please provide valid id to update the record',
})
elif flag == 'delete':
tax_id = obj_tax_master.sudo().browse(int(kw.get('id')))
if tax_id.active == False:
result = json.dumps({
'statusCode': 02,
'statusDesc': 'The record is already archived!!!',
})
else:
tax_id.write({'active':False})
taxes = obj_account_tax.sudo().search([('tax_master_id','=',kw.get('id'))])
for tax in taxes:
tax.write({'active':False})
result = json.dumps({
'statusCode' : 01,
'statusDesc' : 'The record is archived successfully!!!',
})
data = json.loads(result)
self.create_api_log('tax_master', flag, kw, data)
return data
except Exception,e:
result = json.dumps({'statusCode' : 02,'statusDesc' : str(e),})
data = json.loads(result)
self.create_api_log('tax_master', flag, kw, data)
return data
It is solved by using commit function.

#Django - 'list' object has no attribute 'id'

I have this code,
def delivery_date(request):
today = datetime.today().date()
results = [get(today)]
stages = Stage.objects.prefetch_related('Stage').all()
for i in range(3):
results.append(get(results[i]))
results = [{'date': i} for i in results]
stages = [{'menu': s} for s in stages]
for i in results:
for stage in stages:
stage['id'] = stage['menu'].id
stage['name'] = stage['menu'].name
stage['desc'] = stage['menu'].desc
stage['menu'] = stage['menu'].Stage.filter(
delivery_date__exact=i['date'])
stage['menu'] = serializers.serialize('python', stage['menu'])
i['menu'] = stages
i['date'] = i['date'].strftime('%b %-d')
return JsonResponse(results, safe=False)
But the results says,
this image
But if the results has only one date, it works.
Like this,
def delivery_date(request):
today = datetime.today().date()
results = [get(today)]
stages = Stage.objects.prefetch_related('Stage').all()
# for i in range(3):
# results.append(get(results[i]))
results = [{'date': i} for i in results]
stages = [{'menu': s} for s in stages]
for i in results:
for stage in stages:
stage['id'] = stage['menu'].id
stage['name'] = stage['menu'].name
stage['desc'] = stage['menu'].desc
stage['menu'] = stage['menu'].Stage.filter(
delivery_date__exact=i['date'])
stage['menu'] = serializers.serialize('python', stage['menu'])
i['menu'] = stages
i['date'] = i['date'].strftime('%b %-d')
return JsonResponse(results, safe=False)
The results,
[
{
"date" : Oct 25,
"menu" : [
{
"menu" : [
{
"model" : backend.product,
"pk" : 13,
"fields" : {
"name" : Tasty Tempeh,
"desc" : Nasi, Ayam, Wortel, Buncis, Bawang Merah, Bawang Putih, Daun Salam, Serai, Minyak Wijen, Minyak Kelapa Sawit.,
"desc_detail" : ,
"delivery_date" : 2019-10-25,
"avatar" : ,
"stage" : 1
}
}
],
"id" : 1,
"name" : Porridge,
"desc" :
}
}
]
What's wrong with my logic? Can Anyone helps?
it is just you missed that menu is a Dict which has a list as value say temp
and that temp file has a dict at its 0 indexes:
use the following :
stage['menu'][0]['id']

Text giving constantly feedback about current selection

I am writing a script which has an UI in Maya. I have a text box that is supposed to constantly update based on the last item in the users selection list. How would I go about something that constantly keeps checken whithout having the user to push a button or something manually to call a function.
Thx
Edit: Cool that is what I was looking for. Thx. Your script works just fine. I tried implementing that into my big script which resulted in that every button in the UI had to be pushed twice in order to take effect. But I will deal with that later. However testing my own version in a seperate script as follows sometimes produces the following error: 'sl' must be passed a boolean argument
#________________________________________________________________________________________________________________________________________________
import maya.cmds as cmds
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (305,500))
cmds.columnLayout(adj = True)
cmds.text (l = '__________________________________________ \n your current selection has this ID: \n')
curSelTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
def update_label(*_):
upCurrentObjectSel = cmds.ls(sl=True)
upCurrentObjectSelShapes = cmds.listRelatives(upCurrentObjectSel)
upLastobj = upCurrentObjectSelShapes[-1]
print upLastobj
cmds.text(curSelTxt, e=True, label = upLastobj)
cmds.scriptJob(event=("SelectionChanged", update_label), p= curSelTxt)
cmds.showWindow(idManagerUI)
Also, making two of these ScriptJobs makes the script stop working properly entirely.
#________________________________________________________________________________________________________________________________________________
import maya.cmds as cmds
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (305,500))
cmds.columnLayout(adj = True)
cmds.text (l = '__________________________________________ \n your current selection has this ID: \n')
curSelObjTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
curSelShadTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
def update_obj_label(*_):
upCurrentObjectSel = cmds.ls(sl=True)
upCurrentObjectSelShapes = cmds.listRelatives(upCurrentObjectSel)
upLastobj = upCurrentObjectSelShapes[-1]
objID = cmds.getAttr(upLastobj + '.vrayObjectID')
print objID
cmds.text(curSelObjTxt, e=True, label = objID)
def update_shader_label(*_):
upCurrentShaderSel = cmds.ls(sl=True, type= shaderTypes)
upCurrentShaderSelLast = upCurrentShaderSel[-1]
shadID = cmds.getAttr(upCurrentShaderSelLast + '.vrayMaterialId')
cmds.text(curSelShadTxt, e=True, label = shadID)
print shadID
cmds.scriptJob(event=("SelectionChanged", update_obj_label), p= curSelObjTxt)
cmds.scriptJob(event=("SelectionChanged", update_shader_label), p= curSelShadTxt)
cmds.showWindow(idManagerUI)
Edit:
still your latest version of the script produces the error from time to time.
Also, I noticed in my own version of it, that it sometimes works lovely, then not at all, once I e.g. switched my active window to Firefox or so and then get back to Maya, and sometimes it does not work at all. That is with just one of the functions in my script. With both of them (s.below) it is totally unusable. Very unstable results.
import maya.cmds as cmds
def curSelTxtShower():
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (305,500))
cmds.columnLayout(adj = True)
cmds.text (l = '__________________________________________ \n your current selection has this ID: \n')
curSelObjTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
curSelShadTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
def update_obj_label(*_):
upCurrentObjectSelShapes = cmds.listRelatives(s=True) or ["nothing selected"]
upLastobj = upCurrentObjectSelShapes[-1]
if upLastobj is not "nothing selected":
if cmds.attributeQuery('vrayObjectID', node = upLastobj, ex = True) is True:
objID = cmds.getAttr(upLastobj + '.vrayObjectID')
cmds.text(curSelObjTxt, e=True, label = objID)
else:
cmds.text(curSelObjTxt, e=True, label = 'curSel has no ObjID assigned')
def update_shader_label(*_):
upCurrentShaderSel = cmds.ls(sl=True, type= shaderTypes)
upCurrentShaderSelLast = upCurrentShaderSel[-1]
if cmds.attributeQuery('vrayMaterialId', node = upCurrentShaderSelLast, ex = True) is True:
shadID = cmds.getAttr(upCurrentShaderSelLast + '.vrayMaterialId')
cmds.text(curSelShadTxt, e=True, label = shadID)
print shadID
else:
cmds.text(curSelShadTxt, e=True, label = 'curSel has no MatID assigned')
cmds.scriptJob(event=("SelectionChanged", lambda *x: update_obj_label()), p= curSelObjTxt)
cmds.scriptJob(event=("SelectionChanged", lambda *x: update_shader_label()), p= curSelShadTxt)
cmds.showWindow(idManagerUI)
curSelTxtShower()
You need to use a scriptJob to watch for selection change events and respond. You'll want to parent the scriptJob to a particular piece of UI so it deletes itself when the UI object goes away.
An absolutely minimal example looks like this:
import maya.cmds as cmds
wind = cmds.window()
col = cmds.columnLayout()
txt = cmds.text(label="", width = 240)
def update_label(*_):
cmds.text(txt, e=True, label = str(cmds.ls(sl=True)))
cmds.scriptJob(event=("SelectionChanged", update_label), p= txt)
cmds.showWindow(wind)
Edit
This version of OP's code helps avoid the false error message. the actual error was happening when due to an empty selection - but the scriptJob falsely reports it in the previous line:
def scoped():
idManagerUI = cmds.window(title='Vray ID Manager', s = False, wh = (305,500))
cmds.columnLayout(adj = True)
cmds.text (l = '__________________________________________ \n your current selection has this ID: \n')
curSelTxt = cmds.text (l = '', backgroundColor = [0.2, 0.2, 0.2])
def update_label(*_):
# listRelatives works off the current selection already
upCurrentObjectSelShapes = cmds.listRelatives(s=True) or ["nothing selected"]
upLastobj = upCurrentObjectSelShapes[-1]
cmds.text(curSelTxt, e=True, label = upLastobj)
cmds.showWindow(idManagerUI)
cmds.scriptJob(event=("SelectionChanged", update_label), p= idManagerUI)
scoped()