Odoo8 TypeError: cannot concatenate 'str' and 'list' objects - odoo-8

Good night,
i'm extending the odoo8 hr_recruitment module, and i need to show a list of applicants of a job. But when i'm going to access the form view of hr.job i get this error:
domain = domain + [(inverse, 'in', ids)]
TypeError: cannot concatenate 'str' and 'list' objects
Mi code is this:
class hr_job(osv.osv):
_inherit = "hr.job"
_name = "hr.job"
_inherits = {'mail.alias': 'alias_id'}
def _get_attached_docs(self, cr, uid, ids, field_name, arg, context=None):
res = {}
attachment_obj = self.pool.get('ir.attachment')
for job_id in ids:
applicant_ids = self.pool.get('hr.applicant').search(cr, uid, [('job_id', '=', job_id)], context=context)
res[job_id] = attachment_obj.search(
cr, uid, [
'|',
'&', ('res_model', '=', 'hr.job'), ('res_id', '=', job_id),
'&', ('res_model', '=', 'hr.applicant'), ('res_id', 'in', applicant_ids)
], context=context)
return res
def _count_all(self, cr, uid, ids, field_name, arg, context=None):
Applicant = self.pool['hr.applicant']
return {
job_id: {
'application_count': Applicant.search_count(cr, uid, [('job_id', '=', job_id)], context=context),
'documents_count': len(self._get_attached_docs(cr, uid, [job_id], field_name, arg, context=context)[job_id])
}
for job_id in ids
}
_columns = {
'survey_id': fields.many2one('survey.survey', 'Interview Form', help="Choose an interview form for this job position and you will be able to print/answer this interview from all applicants who apply for this job"),
'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="restrict", required=True,
help="Email alias for this job position. New emails will automatically "
"create new applicants for this job position."),
'address_id': fields.many2one('res.partner', 'Job Location', help="Address where employees are working"),
'application_ids': fields.one2many('hr.applicant', 'job_id', 'Applications'),
'partner_id': fields.many2one('res.partner', 'Cliente'),
'application_count': fields.function(_count_all, type='integer', string='Applications', multi=True),
'manager_id': fields.related('department_id', 'manager_id', type='many2one', string='Department Manager', relation='hr.employee', readonly=True, store=True),
'document_ids': fields.function(_get_attached_docs, type='one2many', relation='ir.attachment', string='Applications'),
'documents_count': fields.function(_count_all, type='integer', string='Documents', multi=True),
'user_id': fields.many2one('res.users', 'Recruitment Responsible', track_visibility='onchange'),
'color': fields.integer('Color Index'),
'responsable_id': fields.many2one('res.users', 'Responsable'),
'estado': fields.selection([(u'No Iniciado', u'No Iniciado'),
(u'En Proceso', u'En Proceso'),
(u'Contratado(a)', u'Contratado(a)'),
(u'Suspendido', u'Suspendido'),
(u'Finalizado', u'Finalizado'),
('Otro', 'Otro')], 'Estado del Proceso'),
'otro': fields.char('Otro Estado'),
'fecha_inicio': fields.date('Fecha Inicio'),
'fecha_fin': fields.date('Fecha Fin'),
'partner_id': fields.many2one('res.partner', 'Cliente'),
'applicant_ids': fields.one2many('hr.applicant', 'job_id', 'Candidatos', domain="[('partner_id','=',partner_id)]"),
I think the problem is on domain of applicant_ids...
How can i solve this? Thanks in advance.

You need to change field domain to a list:
'applicant_ids': fields.one2many('hr.applicant',
'job_id',
'Candidatos',
domain=[('partner_id','=',partner_id)])
You can check this answer Understanding OpenERP domain filter?
or
The documentation for domains

Related

How to assert response.data with queryset?

I am testing my API endpoints based on user roles that I have specified using choices in my models.py.
My problem is, when comparing my response.data with the queryset. I am getting this error:
AssertionError: OrderedDict([('count', 1), ('next', None)[228 chars])])]) != <QuerySet [<Project: New Housing 3>]>
def test_projects_list_only_contractor(self):
response = self.client.get(self.url, format='json')
if self.user.role == Role.CONTRACTOR and self.user.is_authenticated:
current_projects = self.user.contractor.projects.all()
self.assertEqual(response.status_code, status.HTTP_200_OK)
# print(response.data)
# [project for project in current_projects]
self.assertEqual(response.data, current_projects )
I have tried converting my current_projects to list, response.data to response.json()['results']
I have also tried using Projects.objects.filter(contractor=self.contractor) for my queryset

How to get an attribute from a relation in Laravel?

This is part of my code:
$form = new Form(new Shop());
$form->tab('terminal', function (Form $form) use ($id) {
$form->hasMany('shopterminal', '', function (Form\NestedForm $form) {
$form->text('terminal_num', 'terminal number')->required();
$form->select('poz_type', 'POS type')->options(['static' => 'one', 'dynamic' => 'two'])->required();
$form->select('psp_id', 'POZ name')->options(Psp::pluck('name', 'id'))->required();
$form->text('sheba', 'sheba number');
$form->text('account_num', 'account number')->required();
$form->select('bank_id', 'bank name')->options(Bank::pluck('name', 'id'))->required();
dd($form);
});
Here is the result of dd($form):
I need to get the value of terminal_image item (which is 15841949062134.png). Any idea how can I get it?
Noted that, neither of below syntax works:
$form->get('terminal_image')
$form->select('terminal_image')
$form->terminal_image
$form()->terminal_image
$form->relation->terminal_image
For your specific example:
$form->form->model->shopterminal[0]->terminal_image
you can use :
$form->form->model->relations['shopterminal']->items[0]->attributes['terminal_image']

In RubyZoho, how to set Task.related_to Lead.id?

I wrote this question up at RubyZoho's forum, but it's languishing there, and it's such a simple question it deserves a wider audience.
I have used RubyZoho to upload a new Lead record to the Zoho CRM API, and now I want to upload a Task with its "related to" field set to that Lead.
Configuring RubyZoho:
RubyZoho.configure do |config|
config.api_key = Setting.plugin_redmine_tigase['zoho_authorization_token']
config.crm_modules = [
'Leads',
'Tasks'
]
config.ignore_fields_with_bad_names = true
config.cache_fields = true
end
Creating the lead:
lead = RubyZoho::Crm::Lead.new
lead.first_name = splut.first
lead.last_name = splut.last
lead.full_name = params[:name]
lead.company = params[:company]
lead.email = params[:mail]
lead.description = description
lead.save
Creating the Task:
found = RubyZoho::Crm::Lead.find_by_email(params[:mail])
lead = found.first
task = RubyZoho::Crm::Task.new
task.related_to = lead.id
task.subject = params[:subject]
task.description = description
task.save
I tried task.related_to = lead.leadid, and got a Task record with a blank "related to" in the Zoho website. And when I try task.related_to = 'Lead'; task.relatedtoid = lead.leadid, I get a undefined method relatedtoid=, naturally because the variable has no setter.
So what am I missing? how do I do this simple thing?
If you look at the documentation it has a section on this
https://www.zoho.com/creator/help/script/creating-a-record-in-zoho-crm.html#create-lead
taskInfo = {
"Task Owner" : input.Owner_Name,
"SMOWNERID" : input.Owner_ID,
"Subject" : input.Subject,
"Description" : input.Description,
"SEMODULE" : "Accounts",
"SEID" : input.Account_ID,
"CONTACTID" : input.Contact_ID};
crmResp = zoho.crm.create("Tasks", taskInfo);
SMOWNERID is the ID of the Owner
SEMODULE can be Accounts or Leads or Cases
SEID is the ID of the Record given in the SEMODULE
CONTACTID is the ID of the contact record
Also if you look at the ruby_zoho_rspec for creating new task
https://github.com/amalc/rubyzoho/blob/950ffe369252f8fad3e7ae67ebddec859c84e19b/spec/ruby_zoho_spec.rb
it 'should save an task record related to an account' do
VCR.use_cassette 'zoho/task_related_to_account' do
a = RubyZoho::Crm::Account.all.first
e = RubyZoho::Crm::Task.new(
:task_owner => a.account_owner,
:subject => "Task should be related to #{a.account_name} #{Time.now}",
:description => 'Nothing',
:smownerid => "#{a.smownerid}",
:status => 'Not Started',
:priority => 'High',
:send_notification_email => 'False',
:due_date => '2014-02-16 16:00:00',
:start_datetime => Time.now.to_s[1, 19],
:end_datetime => '2014-02-16 16:00:00',
:related_to => "#{a.account_name}",
:seid => "#{a.accountid}",
:semodule => 'Accounts'
)
r_expected = e.save
r = RubyZoho::Crm::Task.find_by_activityid(r_expected.id)
r.first.subject[0..20].should eq(r_expected.subject[0..20])
end
So that should help you out link it by specifying SEMODULE and SEID

Django accessing request.user data from form along with file submission

I am trying to display a form with License Type data based on request.user data.
Form works fine when using user as a input variable to the form in the view.
However when I try to upload a file using the same form and use request.File.
I receive following error.
forms.py
from django import forms
class BusinessRequestForm(forms.Form):
business_name = forms.CharField(label='Enter Business Name', widget=forms.Textarea, help_text="Enter the Name of the business you require" )
business_type= forms.ChoiceField(label='Select Your Business Type', choices=BUSINESS_TYPE, help_text="If your business type is not present. Enter details in Additional info" )
license_type =forms.ModelChoiceField(label='Select the license type',queryset=Pricing.objects.none(),help_text="Check Pricing on Main Page Pricing")
additional_detail=forms.CharField(label='Enter any additional details', widget=forms.Textarea, help_text="Give details about your Tax Structure", required=False)
tax_structure=forms.CharField(label='Tax Structure ', widget=forms.Textarea, help_text="Describe Your Tax Structure If Applicable",required=False)
sales_invoice=forms.FileField(help_text="Upload your present Sales Invoice if any",required=False)
purchase_invoice=forms.FileField(help_text="Upload your present Purchase Invoice if any",required=False)
pay_slip=forms.FileField(help_text="Upload your present Pay Slip if any",required=False)
talley_file=forms.FileField(help_text="Upload your present Talley Export if any",required=False)
def __init__(self,input_user,*args,**kwargs):
super(BusinessRequestForm,self).__init__(*args,**kwargs)
select_user=MyProfile.objects.get(user=input_user)
price=Pricing.objects.all().filter(pricing_region=select_user.region).filter(target=select_user.sales_partner)
self.fields['license_type'].queryset=price
models.py
class Business_request(models.Model):
user=models.ForeignKey("auth.User")
business_name=models.CharField("Name of Business Required",max_length=200,help_text="Enter the name of the business")
business_type=models.CharField("Select Business Type",max_length=200,choices=BUSINESS_TYPE,help_text="If your business type is not present,enter in additional details and select the closest type here")
license_type=models.ForeignKey(Pricing)
tax_structure=models.CharField("Tax Structure",max_length=200,help_text="Describe your Tax Structure",blank=True)
additional_details=models.CharField("Enter any additional details",max_length=200,blank=True)
sales_invoice=models.FileField(upload_to='businessReqForm',null=True,blank=True)
purchase_invoice=models.FileField(upload_to='budinessReqForm',null=True,blank=True)
pay_slip=models.FileField(upload_to='budinessReqForm',null=True,blank=True)
talley_file=models.FileField(upload_to='budinessReqForm',null=True,blank=True)
views.py
#login_required
def businessRequestFormView(request):
if request.method == 'POST':
form = BusinessRequestForm(request.FILES,data=request.POST,input_user=request.user,)
if form.is_valid():
business_name=form.cleaned_data['business_name']
business_type=form.cleaned_data['business_type']
license_type=form.cleaned_data['license_type']
additional_details=form.cleaned_data['additional_detail']
tax_structure=form.cleaned_data['tax_structure']
s=Business_request()
s.user=request.user
s.business_name=business_name
s.business_type=business_type
s.license_type=license_type
s.additional_details=additional_details
if request.FILES['sales_invoice']:
sales_invoice=request.FILES['sales_invoice']
s.sales_invoice=sales_invoice
if request.FILES['purchase_invoice']:
purchase_invoice=request.FILES['purchase_invoice']
s.purchase_invoice=purchase_invoice
if request.FILES['pay_slip']:
pay_slip=request.FILES['pay_slip']
s.pay_slip=pay_slip
if request.FILES['talley_file']:
talley_file=request.FILES['talley_file']
s.talley_file=talley_file
s.save()
user=request.user
sender='info#accountingbuddy.org'
subject="AccountingBuddy.Org Business Setup Request Fm %s" % user.first_name
message="Business Name : %s , Business Type: %s , License Type: %s, Additional Details : %s , User %s , Phone %s, Email %s" % (business_name,business_type,license_type, additional_details, request.user,user.myprofile.phone_no,user.email)
recipients = ['keeganpatrao#gmail.com',]
recipients +=[user.email,]
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect(reverse('accountingbuddy:thanks'))
else:
form = BusinessRequestForm(input_user=request.user)
return render(request, 'business_request_form.html', {'form': form})
Error
Environment:
Request Method: POST
Request URL: https://website.com/accountingbuddy/businessrequest/submit/
Django Version: 1.10.7
Python Version: 3.5.2
Installed Applications:
('mezzanine.boot',
'accountingbuddy',
'nova',
'bootstrap3',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.redirects',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.sitemaps',
'mezzanine.conf',
'mezzanine.core',
'mezzanine.generic',
'mezzanine.pages',
'mezzanine.blog',
'mezzanine.forms',
'mezzanine.galleries',
'mezzanine.twitter',
'mezzanine.accounts',
'filebrowser_safe',
'grappelli_safe',
'django.contrib.admin',
'django.contrib.staticfiles',
'django_comments')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'mezzanine.core.request.CurrentRequestMiddleware',
'mezzanine.core.middleware.RedirectFallbackMiddleware',
'mezzanine.core.middleware.TemplateForDeviceMiddleware',
'mezzanine.core.middleware.TemplateForHostMiddleware',
'mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware',
'mezzanine.core.middleware.SitePermissionMiddleware',
'mezzanine.pages.middleware.PageMiddleware')
Traceback:
File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
42. response = get_response(request)
File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/webapps/accounting/accounting_home/myenv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/webapps/accounting/accounting_home/accounting_home/accountingbuddy/views.py" in businessRequestFormView
49. form = BusinessRequestForm(request.FILES,data=request.POST,input_user=request.user,)
Exception Type: TypeError at /accountingbuddy/businessrequest/submit/
Exception Value: __init__() got multiple values for argument 'input_user'

How to get an object from an array Ruby on Rails

In controller I use pluck method to get id and name from my database
#user1 = User.where(name: 'Alex').pluck(:id, :name).first
#user2 = User.where(name: 'Alex').pluck(:id, :name)
It return array
#user1 = `[3, 'Alex']`
#user2 = [[3,'Alex'],[4, 'Alex']]
How can I make object from array, like:
#user1 = <User id:3, name:'Alex'>
#user2 = [<User id:3, name:'Alex'>, <User id:4, name:'Alex'>]
Try:
users = User.where(name: 'Alex').pluck(:id, :name).map do |id, name|
User.new({ id: id, name: name })
end
Or from provided variables:
#user1_obj = User.new(id: #user1[0], name: #user1[1])
#user2_arr = #user2.map { |params| User.new(id: params[0], name: params[1]) }
Please, be advised, you should let ORM do the thing for you, rather building objects on your own.
Hope that helps!

Resources