openerp search view hidden - search

I have a TransientModel which reads from an external data base, thus i created model with functional fields and also declared the search function.
This is a partial column declaration:
_columns = {
'web_id': fields.function(_get_data, string='ID', fnct_search=_search_data, type='integer', method=True, multi='external'),
.....
}
The action for the tree view is
<record id="action_preview_orders" model="ir.actions.act_window">
<field name="name">Preview Orders</field>
<field name="type">ir.actions.act_window</field>
<field name="res_model">external.data</field>
<field name="view_type">tree</field>
<field name="view_mode">tree</field>
<field name="view_id" ref="preview_orders_view"/>
<field name="target">current</field>
<field name="search_view_id" ref="preview_orders_view_filters"/>
</record>
and the search view is
<record id="preview_orders_view_filters" model="ir.ui.view">
<field name="name">Preview Filters</field>
<field name="model">external.data</field>
<field name="arch" type="xml">
<search string="Search Orders">
<filter string="Type" icon="terp-accessories-archiver" domain="[('type_order','=','RO')]"/>
</search>
</field>
</record>
data are showed correctly, my problem is that the search form is not displayed.
It is present into the html, but the div has style=display:hidden
What could I possibly did wrong?
I add the get data function as asked, it is highly dynamic.
I don't know if this could be a problem...
def _get_data(self, cr, uid, ids, field_names, arg, context=None):
res = dict.fromkeys(ids)
for k in ids:
res[k] = dict.fromkeys(self._mapper.keys())
for mk in self._mapper.keys():
fmt = self._mapper[mk].get('format', None)
fnc = self._mapper[mk].get('function', None)
params = self._mapper[mk].get('parameters', None)
if params != None:
indexes = [INDEXES[param] for param in params]
values = [self._rows[k][index] for index in indexes]
if fmt != None:
res[k][mk] = fmt.format(*values)
elif fnc != None:
res[k][mk] = fnc(self, cr, uid, *values)
else:
res[k][mk] = ""
else:
res[k][mk] = ""
return res
the search function is a dummy one:
def _search_data(self, cr, uid, obj, name, args, context):
return [('id','in',[0])]

You need to create function _search_data (for fnct_search=_search_data)
def _get_full_name(self, cr, uid, ids, field, arg, context=None):
res = {}
for g in self.browse(cr, uid, ids, context):
if g.category_id:
res[g.id] = '%s / %s' % (g.category_id.name, g.name)
else:
res[g.id] = g.name
return res
def _search_group(self, cr, uid, obj, name, args, context=None):
operand = args[0][2]
operator = args[0][1]
lst = True
if isinstance(operand, bool):
domains = [[('name', operator, operand)], [('category_id.name', operator, operand)]]
if operator in expression.NEGATIVE_TERM_OPERATORS == (not operand):
return expression.AND(domains)
else:
return expression.OR(domains)
if isinstance(operand, basestring):
lst = False
operand = [operand]
where = []
for group in operand:
values = filter(bool, group.split('/'))
group_name = values.pop().strip()
category_name = values and '/'.join(values).strip() or group_name
group_domain = [('name', operator, lst and [group_name] or group_name)]
category_domain = [('category_id.name', operator, lst and [category_name] or category_name)]
if operator in expression.NEGATIVE_TERM_OPERATORS and not values:
category_domain = expression.OR([category_domain, [('category_id', '=', False)]])
if (operator in expression.NEGATIVE_TERM_OPERATORS) == (not values):
sub_where = expression.AND([group_domain, category_domain])
else:
sub_where = expression.OR([group_domain, category_domain])
if operator in expression.NEGATIVE_TERM_OPERATORS:
where = expression.AND([where, sub_where])
else:
where = expression.OR([where, sub_where])
return where
_columns = {
'full_name': fields.function(_get_full_name, type='char', string='Group Name', fnct_search=_search_group),
}
check out full name in res.groups table

def _get_full_name(self, cr, uid, ids, field, arg, context=None):
res = {}
for g in self.browse(cr, uid, ids, context):
if g.partner_id.new_ic_number:
res[g.id] = g.partner_id.new_ic_number
elif g.partner_id.old_ic_number:
res[g.id] = g.partner_id.old_ic_number
#~ res[g.id] = '%s / %s' % (g.category_id.name, g.name)
else:
res[g.id] = ''
return res
def _search_customer_ic(self, cr, uid, obj, name, args, context=None):
ids = set()
partner_obj = self.pool.get('res.partner')
partner_ids1 = partner_obj.search(cr,uid,[('new_ic_number','ilike',args[0][2])])
partner_ids2 = partner_obj.search(cr,uid,[('old_ic_number','ilike',args[0][2])])
partner_ids = partner_ids1+partner_ids2
partner_ids = list(set(partner_ids))
agreement_ids = self.search(cr,uid,[('partner_id','in',partner_ids)])
return [('id','in',agreement_ids)]
_columns = {
'ic_number':fields.function(_get_full_name, type='char', string='Customer IC', fnct_search=_search_customer_ic),
}
This is sample code which is done to retreive customer_ic number based search in agreement table(custom table) where we have partner_id and no ic number ,so i retrieve data from res.partner (old_ic_number or new_ic_number and same functional field by search method to search in agreement table

Related

how to work with foreign key field in django

Hi Everyone i am working work django framework, where i used to upload excel file in Dailytrip table, current i get car_mumber from car table, but now i need to store car_number from Car_team table also team_id, i am storing car_id and team_id in car_team table also i need to store team_id in dailytrip table automaticlly based on car_id(car_number) i am to much confuse how to i work that, pls help me out
models.py
class Car_team(BaseModel):
team = models.ForeignKey(
Team,
models.CASCADE,
verbose_name='Team',
null=True,
)
car=models.ForeignKey(
Car,
models.CASCADE,
verbose_name='Car',
null=True)
city =models.ForeignKey(
City,
models.CASCADE,
verbose_name='City',
)
start_date=models.DateField(null=True, blank=True)
end_date=models.DateField(null=True, blank=True)
views.py
def add_payout_uber_daily_data(request):
if request.method == 'POST':
form = UberPerformanceDataForm(request.POST, request.FILES, request=request)
if form.is_valid():
date = form.cleaned_data['date']
excel_file = request.FILES['file']
df = pd.read_excel(excel_file)
is_na = pd.isna(df['Date']).sum().sum() + pd.isna(df['Name']).sum().sum() + pd.isna(df['UUID']).sum().sum() + pd.isna(df['Net Fare With Toll']).sum().sum() + pd.isna(df['Trips']).sum().sum() + pd.isna(df['Uber KMs']).sum().sum() + pd.isna(df['CashCollected']).sum().sum() + pd.isna(df['UberToll']).sum().sum() + pd.isna(df['Tips']).sum().sum() + pd.isna(df['Hours Online']).sum().sum() + pd.isna(df['Ratings']).sum().sum() + pd.isna(df['Acceptance Rate']).sum().sum() + pd.isna(df['Cancellation Rate']).sum().sum()
error_list = []
if is_na > 0:
error_list.append('Found #N/A or blank values in the sheet. Please correct and re-upload')
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
date_match = True
for d in df['Date']:
if str(d.strftime("%Y-%m-%d")) != str(date):
date_match = False
break
if not date_match:
error_list.append('Some dates are not matching in excel')
if len(error_list) > 0:
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
DailyTrip.objects.filter(date=date).update(is_active=0)
for i in df.index:
uuid = df['UUID'][i]
driver_id = None
car_id = None
fleet_id = None
manager_id = None
try:
driver = Driver.objects.get(uber_uuid=uuid)
driver_id = driver.id
except Driver.DoesNotExist:
driver_id = None
#replce car code and store car_number,car_id,team_id via car_team only this logic need to change current get car_number direct car table but we need car_number vai foriegn key
try:
car = Car.objects.get(car_number=df["Car Number"][i])
car_id = car.id
manager_id = car.manager_id
except Car.DoesNotExist:
car_id = None
try:
fleet = Fleet.objects.get(name=df["Fleet Name"][i])
fleet_id = fleet.id
except Fleet.DoesNotExist:
fleet_id = None
name = df['Name'][i]
car_number = df['Car Number'][i]
fare_total = df['Net Fare With Toll'][i]
trips = df['Trips'][i]
pool_trips = 0
hours_online = df['Hours Online'][i]
total_km = df['Uber KMs'][i]
cash_collected = abs(df['CashCollected'][i])
toll = df['UberToll'][i]
tip_amount = df['Tips'][i]
fare_avg = float(fare_total)/int(trips)
fare_per_hour_online = float(fare_total)/float(hours_online)
fare_per_km = fare_total/total_km
trips_per_hour = trips/hours_online
km_per_trip = total_km/trips
rating = df['Ratings'][i]
acceptance_rate_perc = float(df['Acceptance Rate'][i])/100
driver_cancellation_rate = float(df['Cancellation Rate'][i])/100
obj, created = DailyTrip.all_objects.update_or_create(
date=date, uuid=uuid,
defaults={
'car_id': car_id,
'manager_id': manager_id,
'car_number': car_number,
'driver_id': driver_id,
'car_id': car_id,
'fleet_id': fleet_id,
'driver_name': name,
'fare_total': fare_total,
'trips': trips,
'pool_trips': pool_trips,
'hours_online': hours_online,
'total_km': total_km,
'cash_collected': cash_collected,
'toll': toll,
'tip_amount': tip_amount,
'fare_avg': fare_avg,
'fare_per_hour_online':fare_per_hour_online,
'fare_per_km':fare_per_km,
'trips_per_hour': trips_per_hour,
'km_per_trip': km_per_trip,
'rating': rating,
'acceptance_rate_perc': acceptance_rate_perc,
'driver_cancellation_rate': driver_cancellation_rate,
'is_active': 1,
'comments': None}
)
if len(error_list) > 0:
DailyTrip.objects.filter(date=date).update(is_active=0)
context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, }
return render(request, 'add_payout_uber_daily_data.html', context=context)
else:
messages.success(request, 'Daily Trips added Successfully...')
return redirect('/fleet/payout/daily_data/add/uber')
else:
form = UberPerformanceDataForm(initial={})
context = {
'menu_payout': 'active',
'submenu_daily_data': 'active',
'form': form,
}
return render(request, 'add_payout_uber_daily_data.html', context=context)
You can try that :
to get car_number from car_team -->
car_team = car_team.objects.objects.all().last() # to get the last car_team for example
car_number = car_team.car.car_number # to get the car number from the car_team
try:
car = Car.objects.get(car_number=df["Car Number"][i])
car_id = car.id
car1=Car_team.objects.filter(car_id=car_id)
if car1:
team_id=car1[0].team_id
else:
team_id=None
except Car.DoesNotExist:
car_id = None
team_id= None

Overwrite a field: odoo.exceptions.CacheMiss: ('stock.picking.batch(31,).picking_batch_moves', None)

I'm trying to group all moves in the stock.picking in the stock.picking.batch
it work fine, but I got this error when I want to overwrite the batch_id in stock.picking:
File "/opt/odoo/odoo12/odoo/api.py", line 1051, in get
raise CacheMiss(record, field)
odoo.exceptions.CacheMiss: ('stock.picking.batch(31,).picking_batch_moves', None)
this is my code:
class StockMove(models.Model):
_inherit = 'stock.move'
pbm_id = fields.Many2one('stock.picking.batch.move', string='Batche moves')
class StockPickingBatchLine(models.Model):
_name = 'stock.picking.batch.move'
_description = 'Opération des mouvement des transfer'
batch_id = fields.Many2one(
'stock.picking.batch', string='Picking batch', required=True, ondelete='cascade')
product_id = fields.Many2one(
'product.product', string='Produit', readonly=True, required=True)
product_uom_id = fields.Many2one(
'uom.uom', string='Unité de mesure', readonly=True, required=True)
product_uom_qty = fields.Float('A faire', default=0.0, digits=dp.get_precision('Product Unit of Measure'),
readonly=True, )
location_id = fields.Many2one(
'stock.location', 'From', readonly=True, required=True)
location_dest_id = fields.Many2one(
'stock.location', 'To', readonly=True, required=True)
move_lines = fields.One2many(
'stock.move', 'pbm_id', string='Movement de stock')
class StockPickingBatch(models.Model):
_inherit = 'stock.picking.batch'
picking_batch_moves = fields.One2many('stock.picking.batch.move', 'batch_id', string='Lignes des mouvements',
compute='_compute_picking_get_batch_lines', readonly=False, store=True,
)
#api.depends('picking_ids', 'picking_ids.move_lines')
def _compute_picking_get_batch_lines(self):
batch_moves_obj = self.env['stock.picking.batch.move']
linked = self.env['stock.picking.batch.move']
ml_ids = self.env['stock.picking.batch.move.line']
for batch in self:
if isinstance(batch.id, models.NewId):
continue
req = """
SELECT sp.batch_id
,product_id
,product_uom product_uom_id
,sm.location_id
,sm.location_dest_id
,sm.state
,sm.picking_type_id
,sum(product_uom_qty) product_uom_qty
,array_agg(DISTINCT sm.id) moves
FROM stock_move sm
JOIN stock_picking sp ON sp.id = sm.picking_id
WHERE sp.batch_id IN (%s)
GROUP BY sp.batch_id
,product_id
,product_uom
,sm.location_id
,sm.state
,sm.picking_type_id
,sm.location_dest_id"""
self.env.cr.execute(req, (batch.id,))
fetched_lines = self.env.cr.fetchall()
batch_moves = batch_moves_obj.search([('batch_id', '=', batch.id)])
linked = batch_moves_obj
move_lines = []
for line in fetched_lines:
# search for existing line to update
matched = batch_moves.filtered(lambda x: x.product_id.id == line[1] and
x.product_uom_id.id == line[2] and
x.location_id.id == line[3] and
x.location_dest_id.id == line[4] and
x.state == line[5]
)
line_data = {
'batch_id': batch.id,
'product_id': line[1],
'product_uom_id': line[2],
'location_id': line[3],
'location_dest_id': line[4],
'state': line[5],
'picking_type_id': line[6],
'product_uom_qty': line[7],
'move_lines': [(6, 0, line[8])],
}
move_lines.extend(line[8])
if matched.exists():
matched.with_context(recompute=False).write(line_data)
linked += matched
else:
linked += batch_moves_obj.with_context(
recompute=False).create(line_data)
batch.picking_batch_moves = linked or False
Try:
batch.write({'picking_batch_moves': linked or False})
It should work

Why do I keep getting the AttributeError: 'str' object has no attribute 'Student' when running my program

I am trying to run a program that implements Object Oriented Programming to help a student register for a course. I keep running into an Attribute Error and can't seem to figure out where my code went wrong.
I initially thought it had something to do with the fact that I had not implemented the self parameter in all the method def statements. But after I fixed this, I still encountered the same error message.
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
TRUE = True
FALSE = False
COURSES_INPUT = 'courses-sample.txt'
STUDENTS_INPUT= 'students-sample.txt'
import student
import course
def main():
process_students()
process_courses()
option = get_option()
while option != 5:
if option == 1:
course_num = input('please input course number of course you wish to add: ')
add_course = new_student.add_course(course_num)
while add_course == FALSE:
print('The course requested for add does not exist. Please Try Again.')
course_num = input('Please input course number of course you wish to add: ')
if new_course.space_available() == TRUE:
new_course.enroll_student()
else:
print('Class requested does not have any seats available.')
if option == 2:
course_num = input('please input course number of course you wish to drop: ')
drop_course = new_student.drop_course(course_num)
while drop_course == FALSE:
print('The enrolled course requested for drop does not exist. Please Try Again.')
course_num = input('Please input course number of course you wish to drop: ')
new_course.drop_student()
if option == 3:
print_student_info(student_dict)
if option == 4:
print_course_schedule(course_dict)
option = get_option()
write_updated('students-updated.txt',student_dict)
write_updated('courses-updated.txt',course_dict)
def print_menu():
print("1. Add course")
print("2. Drop course")
print("3. Print student's schedule")
print("4. Print course schedule")
print("5. Done")
print("")
def get_option():
print_menu()
choice = input("What would you like to do? ")
while choice not in range(1,6):
print_menu()
choice = input("Choice is invalid. What would you like to do? ")
return choice
def process_students():
student_dict = {}
student_info = open(STUDENTS_INPUT,"r")
for student in student_info:
info_list = student.split(":")
new_id = info_list[0]
first_name = info_list[1]
last_name = info_list[2]
course_list = info_list[3:]
new_student = student.Student(new_id, first_name, last_name, course_list)
print(new_student.line_for_file())
student_dict[new_eid] = new_student
student_info.close()
def process_courses():
course_dict = {}
course_info = open(COURSES_INPUT,"r")
for course in course_info:
info_list = course.split(";")
unique_num = info_list[0]
class_name = info_list[1]
prof = info_list[2]
seats = info_list[3]
capacity = info_list[4]
new_course = course.Course(unique_num, class_name, prof, seats, capacity)
course_dict[unique_num] = new_course
course_info.close()
def print_course_schedule(course_dict):
for value in course_dict:
print(value)
def print_student_info(student_dict):
for value in student_dict:
print(value)
def get_id():
eid = input("What is the UT EID? ")
while eid not in student_dict:
eid = input("Invalid UT EID. Please re-enter: ")
return eid
def get_unique():
unique = input("What is the course unique number? ")
while unique not in course_dict:
unique = input("Invalid unique number. Please re-enter: ")
return unique
def write_updated(filename,dictionary):
output_file = open(filename,'w')
for key in dictionary:
output_file.write(dictionary[key])
output_file.close()
main()
Error Message:
Traceback (most recent call last):
File "C:\Users\njung\Downloads\MIS 304 Final Project\untitled folder\Nguyen_Calvin_Jung_Nicholas-FP.py", line 132, in <module>
main()
File "C:\Users\njung\Downloads\MIS 304 Final Project\untitled folder\Nguyen_Calvin_Jung_Nicholas-FP.py", line 24, in main
process_students()
File "C:\Users\njung\Downloads\MIS 304 Final Project\untitled folder\Nguyen_Calvin_Jung_Nicholas-FP.py", line 83, in process_students
new_student = student.Student(new_id, first_name, last_name, course_list)
AttributeError: 'str' object has no attribute 'Student'
>>>
I also have the classes used stored in separate files (was required for the program) and have imported the modules containing these classes into main as you can see at the top.
Your error is AttributeError: 'str' object has no attribute 'Student'
Looking at the trace, it seems that it originates from this code:
student_info = open(STUDENTS_INPUT,"r")
for student in student_info:
info_list = student.split(":")
new_id = info_list[0]
first_name = info_list[1]
last_name = info_list[2]
course_list = info_list[3:]
new_student = student.Student(new_id, first_name, last_name, course_list)
Here you've opened a file. student_info is the file, and you iterate over the lines in the file. Each line student is a string.
You later call student.Student(new_id, first_name, last_name, course_list), but since student is just a string, it naturally does not contain a Student method.

Pos Tag Lemmatize giving only one row in output

Using Pos Tag on tokenize data, it is coming into form of word, pos_tag.
When passing the same for lemmatization, only the first value is getting lemmatized.
Dataframe with two columns-
ID Text
1 Lemmatization is an interesting part
After tokenize and removing stop words -
ID Tokenize_data
1 'Lemmatization', 'interesting', 'part'
#Lemmatization with postag
#Part of Speech Tagging
df2['tag_words'] = df2.tokenize_data.apply(nltk.pos_tag)
#Treebank to Wordnet
from nltk.corpus import wordnet
def get_wordnet_pos(treebank_tag):
if treebank_tag.startswith('J'):
return wordnet.ADJ
elif treebank_tag.startswith('V'):
return wordnet.VERB
elif treebank_tag.startswith('N'):
return wordnet.NOUN
elif treebank_tag.startswith('R'):
return wordnet.ADV
else:
return None
from nltk.stem.wordnet import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
def tagging(text):
#tagged = nltk.pos_tag(tokens)
for (word, tag) in text:
wntag = get_wordnet_pos(tag)
if wntag is None:# not supply tag in case of None
lemma = lemmatizer.lemmatize(word)
else:
lemma = lemmatizer.lemmatize(word, pos=wntag)
return lemma
tag1 = lambda x: tagging(x)
df2['lemma_tag'] = df2.tag_words.apply(tag1)
Output is coming as -
ID Lemma_words
1 'Lemmatize'
Expected -
ID Lemma_words
1 'Lemmatize', 'interest', 'part'
Below function works -
My code was not retaining the values of all the tuples inside my pos tag list hence only one value was coming in output
def lemmatize_sentence(text):
#tokenize the sentence and find the POS tag for each token
nltk_tagged = nltk.pos_tag(nltk.word_tokenize(text))
#tuple of (token, wordnet_tag)
wordnet_tagged = map(lambda x: (x[0], nltk_tag_to_wordnet_tag(x[1])), nltk_tagged)
lemmatized_sentence = []
for word, tag in wordnet_tagged:
if tag is None:
#if there is no available tag, append the token as is
lemmatized_sentence.append(word)
else:
#else use the tag to lemmatize the token
lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))
return lemmatized_sentence

Dictionary with functions versus dictionary with class

I'm creating a game where i have the data imported from a database, but i have a little problem...
Currently i get a copy of the data as a dictionary, which i need to pass as argument to my GUI, however i also need to process some data, like in this example:
I get the data as a dict (I've created the UseDatabase context manager and is working):
def get_user(name: str, passwd: str):
user = {}
user['name'] = name
user['passwd'] = passwd
with UseDatabase() as cursor:
_SQL = "SELECT id, cash, ruby FROM user WHERE name='Admin' AND password='adminpass'"
cursor.execute(_SQL)
res = cursor.fetchall()
if res:
user['id'] = res[0][0]
user['cash'] = res[0][1]
user['ruby'] = res[0][2]
return user
return res
.
.
.
def get_activities():
with UseDatabase() as cursor:
_SQL = "SELECT * FROM activities WHERE user_id='2'"
cursor.execute(_SQL)
res = cursor.fetchall()
if res:
ids = [i[0] for i in res]
activities = {}
for i in res:
activities[i[0]] = {'title':i[1],'unlock':i[2],'usr_progress':i[3]}
return (ids, activities)
return res
Need it as a dict in my GUI ("content" argument):
class SideBar:
def __init__(self, screen: 'pygame.display.set_mode()', box_width: int, box_height: int, content: dict, font: 'font = pygame.font.Font()'):
#content dict: {id: {'title':'','unlock':'','usr_progress':''},...}
self.box_width = box_width
self.box_height = box_height
self.box_per_screen = screen.get_height() // box_height
self.content = content
self.current_box = 1
self.screen = screen
self.font = font
self.generate_bar()
def generate_bar (self):
active = [i for i in self.content.keys() if i in range(self.current_box, self.current_box+self.box_per_screen)]
for i in range(self.box_per_screen):
gfxdraw.box(self.screen,pygame.Rect((0,i*self.box_height),(self.screen.get_width()/3,self.screen.get_height()/3)),(249,0,0,170))
self.screen.blit(self.font.render(str(active[i]) + ' - ' + self.content[active[i]]['title'], True, (255,255,255)),(10,i*self.box_height+4))
for i in range(self.box_per_screen):
pygame.draw.rect(self.screen,(50,0,0),pygame.Rect((0,i*self.box_height),(self.screen.get_width()/3,self.screen.get_height()/3)),2)
But still need to make some changes in the data:
def unlock_act(act_id):
if user['cash'] >= activities[act_id]['unlock'] and activities[act_id]['usr_progress'] == 0:
user['cash'] -= activities[act_id]['unlock']
activities[act_id]['usr_progress'] = 1
So the question is: in this situation should i keep a copy of the data as dict, and create a class with it plus the methods i need or use functions to edit the data inside the dict?

Resources