Kotti / deform_ext_autocomplete - How do I use ExtendedAutocompleteInputWidget in Kotti? - pyramid

I'm trying to use ExtendedAutocompleteInputWidget from deform_ext_autocomplete so a widget will have autocomplete. The reason I want to use ExtendedAutocompleteInputWidget is so I can get key/display value pairs, where as the normal autocomplete only deals with the Display value.
Based on documentation for the widget, this is what I have so far:
In my_project/resources.py:
class MyContent(Content):
id = Column(Integer(), ForeignKey('contents.id'), primary_key=True)
person = Column(Unicode())
type_info = Content.type_info.copy(
name=u'MyContent',
title=u'MyContent',
add_view=u'add_mycontent',
addable_to=[u'Document'],
)
In my_project/views/edit.py:
PERSONS = {'jhendrix': 'Jimi Hendrix',
'jpage': 'Jimmy Page',
'jbonham': 'John Bonham',
'bcobham': 'Billy Cobham'}
def display_value(field, person_id):
return PERSONS.get(person_id, '')
class MyContentSchema(ContentSchema):
title = colander.SchemaNode(
colander.String(),
title=_(u'Title'),
)
person = colander.SchemaNode(
colander.String(),
widget=ExtendedAutocompleteInputWidget(
display_value = display_value,
delay=3,
values="/ajax_search"))
#view_config(name='edit',context=MyContent,permission='edit',
renderer='kotti:templates/edit/node.pt')
class MyContentEditForm(EditFormView):
schema_factory = MyContentSchema
#view_config(name=MyContent.type_info.add_view, permission='add',
renderer='kotti:templates/edit/node.pt')
class MyContentAddForm(AddFormView):
schema_factory=MyContentSchema
add = MyContent
item_type = u"MyContent"
#view_config(name='ajax_search',renderer='json')
def ajax_search(request):
term = request.GET['term'].lower()
res = []
for person_id, name in PERSONS.items():
if term not in name.lower():
continue
res.append({'displayed':name,
'stored':person_id,
})
return res
Unfortunately, I am getting errors:
pyramid.httpexceptions.HTTPNotFound: The resource could not be found.
During handling of the above exception, another exception occurred:
deform.exception.TemplateError: deform.exception.TemplateError: ext_autocomplete_input.pt
- Expression: "field.serialize(cstruct).strip()"
- Filename: ... python3.5/site-packages/deform/templates/mapping_item.pt
- Location: (line 29: col 34)
- Source: ... place="structure field.serialize(cstruct).strip()"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Expression: "child.render_template(item_template)"
- Filename: ... ite/lib/python3.5/site-packages/deform/templates/form.pt
- Location: (line 47: col 32)
- Source: ... ace="structure child.render_template(item_template)"/>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Arguments: target_language: <NoneType - at 0xa40040>
field: <Field - at 0x7f2fc9b234a8>
category: default
cstruct: <_null - at 0x7f2fcd643c50>
repeat: {...} (0)
error_class: error
description:
input_append: <NoneType - at 0xa40040>
structural: False
input_prepend: <NoneType - at 0xa40040>
hidden: False
title: Person
required: True
oid: deformField4
Am I approaching trying to use the widget the wrong way?
I'm using Kotti 2.0.1.

Related

Read YAML components from variable in groovy

I have a code like below
import groovy.yaml.YamlSlurper
def configYaml = '''\
---
application: "Sample App"
users:
- name: "mrhaki"
likes:
- Groovy
- Clojure
- Java
- name: "Hubert"
likes:
- Apples
- Bananas
connections:
- "WS1"
- "WS2"
'''
// Parse the YAML.
def config = new YamlSlurper().parseText(configYaml)
def data1 = "users"
def date2 = "name"
println config.users.likes // printing correct
println config.$data1.$data2 // getting error
I need to print elements from users.name and I need to print it from variable form.
like "println config.$data1.$data2"
You can do something like below.
def config = new YamlSlurper().parseText(configYaml)
def data1 = "users"
def data2 = "name"
println config.users.likes
println config."$data1"."$data2"

Many2many field tableundefined odoo, can't get multiple many2many fields

I have multiple Many2many fields but I'm getting the following error:
relation stream doesn't exist,undefined-table
I cannot find where this error is occurring. Can someone help me fix this error?
class College(models.Model):
_name = 'module5_college'
_description = 'College Info'
_rec_name = 'clg'
clg = fields.Char("College Name")
uni = fields.Char("Affiliated to")
cou = fields.Many2many('module5_stream',string="Stream")
class Stream(models.Model):
_name = 'module5_stream'
_description = 'Stream info'
_rec_name = 'cou'
cou = fields.Selection([
('BTECH', 'BTECH'),
('MTECH', 'MTECH'),
('MCA', 'MCA')],"Stream")
cou_mode = fields.Selection([
('Regular','Regular'),
('Lateral','Lateral'),
('Distance','Distance')],"Course Mode")
sem_no = fields.Integer("No of semesters")
# full_score = fields.Integer(compute='score_calc',string="Score")
sem = fields.Many2many('module5_sem',"Semesters")
class Semester(models.Model):
_name = 'module5_sem'
_rec_name = 'id'
sem_no = fields.Char("Semester No")
sub = fields.Many2many('module5_subject',"Subjects")
You have to follow this example because this is the way to create many2many field:
employees_ids = fields.many2many('Employees.Employees', 'tasks_employees_rel', 'task_id', 'employee_id', 'Employees assigned to task')
To give you a better example.
A employee can be assigned to many tasks
A task can be assigned to many employees
So you have a many2many relation, so that means that you have to create a new table containing both keys.

i have added a field in existing module "hr.payslip" from my module.How to show the data of that field

an existing module is present i.e hr.payslip,In that module i have added a field from my module . now i want to display the value of that field in hr.payslip module.
models/emailpayslip.py
#api.multi #Decorate a record-style method where 'self' is a recordset. The method typically defines an operation on records.
def send_email(self):
ir_model_data = self.env['ir.model.data']
payslip_obj = self.env['hr.payslip']
ids = self.env.context.get('active_ids', [])
ctx = dict()
employee_name = ''
for id_vals in ids:
payslip_browse = payslip_obj.browse(id_vals)
global email
email = payslip_browse.employee_id.work_email
store_email.sql_example(self,email)#calling method of store_email model
if payslip_browse.employee_id.work_email:
template_id = ir_model_data.get_object_reference('Payslip', 'email_template_payslip')[1]
ctx.update({
'default_model': 'hr.payslip',
'default_res_id': payslip_browse.id,
'default_use_template': bool(template_id),
'default_template_id': template_id,
'default_composition_mode': 'comment',
'email_to': payslip_browse.employee_id.work_email,
})
mail_id = self.env['mail.template'].browse(template_id).with_context(ctx).send_mail(payslip_browse.id, True)
This model is used to create a new table in database and store email to which the payslip is send and date of payslip send
class store_email(models.Model):
_name = "store.email"
sendemail = fields.Char(
string='Send Email',
default=lambda self: self._get_default_name(),
)
no_of_times = fields.Integer(string='No of Times')
date_of_email_send = fields.Date(
string="Date of Email",
default=lambda self: fields.datetime.now())
#api.model
def _get_default_name(self):
return "test"
#api.multi
def sql_example(self,temp):
dob = datetime.today()
self.env.cr.execute("SELECT * FROM store_email WHERE sendemail = %s",(temp,))
res = self.env.cr.fetchall()
if res == []:
count = 1
self.env.cr.execute("INSERT INTO store_email (sendemail,no_of_times,date_of_email_send) VALUES (%s,%s,%s)",(temp,count,dob))
self.env.cr.commit()
else:
for x in res:
count = x[7] + 1
self.env.cr.execute("UPDATE store_email SET date_of_email_send=%s,no_of_times=%s WHERE sendemail=%s",(dob,count,temp))
self.env.cr.commit()
Model to add a field in hr.payslip ,Which show last payslip send date
class Add_Field(models.Model):
_inherit = "hr.payslip"
last_payslip_send = fields.Date(string='Last Payslip Send')
#api.multi
def last_send_payslip(self):
self.env.cr.execute("SELECT * FROM store_email WHERE sendemail=%s",(email,))
res = self.env.cr.fetchall()
my addfile.xml
add_newfield
screenshort of the page where i have added the field
this page cntain the screenshort
You can use compute or default function to load value in to field or you can also pass value while creating record
default function example:
name = fields.Char(
string='Name',
default=lambda self: self._get_default_name(),
)
#api.model
def _get_default_name(self):
return "test"
Refer this link for computed fields

Boto3/Lambda - Join multiple outputs from a loop and send in one email using AWS SNS

New to Python/Boto3, this should be an easy one but still learning :)
I have a Lambda function which creates a number of snapshots and works fine:
def create_snapshot():
volumes = ec2_client.describe_volumes(
Filters=[
{'N'...
...
for volume in volumes...
....
snap_name = 'Backup of ' + snap_desc
....
snap = ec2_client.create_snapshot(
VolumeId=vol_id,
Description=snap_desc
)
I then want to receive an email from AWS SNS to let me know which snapshots the function created, which I do using:
message = sns.publish(
TopicArn=SNSARN,
Subject=("Function executed"),
Message=("%s created" % snap_name)
)
The issue is that this creates an email for each snapshot, instead of one email listing all the snapshots. Should I create another function that calls all values produced by snap_desc, or can I send all values for snap_desc in the function? And most importantly what's the best way of doing this?
Cheers!
Scott
####################### UPDATE (Thanks #omuthu) #######################
I set an array inside and outside the loop, and put the string into the message. This produced the following being sent in one message:
The following snapshots have been created:
['vol-0e0b9a5dfb8379fc0 (Instance 1 - /dev/sda1)', 'vol-03aac6b65df64661e (Instance 4 - /dev/sda1)', 'vol-0fdde765dfg452631 (Instance 2 - /dev/sda1)', 'vol-0693a9568b11f625f (Instance 3 - /dev/sda1)', etc.
Okay got it sorted, finally!
def create_snapshot():
volumes = ec2_client.describe_volumes(
Filters=[
{'N'...
...
inst_list = []
for volume in volumes...
vol_id = volume['VolumeId']
....
snap_desc = vol_id
for name in volume['Tags']:
tag_key = name['Key']
tag_val = name['Value']
if tag_key == 'Name':
snap_desc = vol_id + ' (' + tag_val + ')'
....
....
....
if backup_mod is False or (current_hour + 10) % backup_mod != 0:
...
continue
else:
print("%s is scheduled this hour" % vol_id)
for name in volume['Tags']:
inst_tag_key = name['Key']
inst_tag_val = name['Value']
if inst_tag_key == 'Name':
inst_list.append(inst_tag_val)
snap = ec2_client.create_snapshot(
VolumeId=vol_id,
Description=snap_desc,
)
print("%s created" % snap['SnapshotId'])
msg = str("\n".join(inst_list))
if len(inst_list) != 0:
message = sns.publish(
TopicArn=SNSARN,
Subject=("Daily Lambda snapshot function complete"),
Message=("The following snapshots have been created today:\n\n" + msg + "\n")
)
print("Response: {}".format(message))

Typecasting in Groovy

I am trying to parse an yaml file in Groovy. However I am facing issue while typecasting the result to Map object.
Here is my logic
import org.yaml.snakeyaml.Yaml
import java.util.Map
Reader reader = null
int tokenCount = 0
def Map map = null
StringTokenizer st = new java.util.StringTokenizer("Country.State.City", ".")
reader = new FileReader("filepath")
String val = null
Yaml yaml = new Yaml()
map = (Map) yaml.load(reader)
tokenCount = st.countTokens()
for (i=1; i < tokenCount; i++) {
String token = st.nextToken()
map = (Map) map.get(token)
}
val = map.get(st.nextToken()).toString()
However I am getting error at line:
map = (Map) map.get(token)
where it says:
"org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'some value' with class 'java.lang.String' to class 'java.util.Map' error at line: 15"..
Where I am going wrong?
your provided yaml file is syntactically incorrect. This is a fixed version:
location: C:\\Users\\amah11\\Desktop\\New folder
type: hi
Header:
Code:
Start: 0
End: 2
value: H00
Owner:
Start: 3
End: 5
value: AIM
User:
Start: 6
End: 8
Value: AIM
number: 1
Note that Code: **Static** in the original messes things up. And all the keys on the final level need a space after the : (e.g. Start:3 is wrong).
The actual error message is:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Static Start:0 End:2 value:H00' with class 'java.lang.String' to class 'java.util.Map'
which is rather clear in showing, that there is something wrong with the original file.
You might want to consider using an editor, that detects errors like this right away.
An alternative to the original code, would be the use of inject on the tokenizer:
def map = new Yaml().load(new FileReader("cardconfig.yml"))
println new StringTokenizer('Header.Code.End', '.').inject(map) { r, s -> r.get(s) }
BTW: you don't need to import java.util in groovy.

Resources