i'm using odoo 8 and i have develop a custom module for biometric device and it shows error
userHasUserDevice = biometric_user_obj.search([('employee_id', '=', int(values['employee_id'])),
KeyError: 'employee_id'
i tried to fix the problem but it always display the same problem. Any idea for help please ?
Traceback
Traceback (most recent call last):
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\http.py", line 544, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\http.py", line 581, in dispatch
result = self._call_function(**self.params)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\http.py", line 317, in _call_function
return checked_call(self.db, *args, **kwargs)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\service\model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\http.py", line 314, in checked_call
return self.endpoint(*a, **kw)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\http.py", line 810, in __call__
return self.method(*args, **kw)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\http.py", line 410, in response_wrap
response = f(*args, **kw)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\addons\web\controllers\main.py", line 948, in call_button
action = self._call_kw(model, method, args, {})
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\addons\web\controllers\main.py", line 936, in _call_kw
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\api.py", line 268, in wrapper
return old_api(self, *args, **kwargs)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\addons\hr_biometric_machine\models\biometric_data_wizard.py", line 22, in import_attendance
biometric_attendance.crate_attendance_in_openep()
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\api.py", line 266, in wrapper
return new_api(self, *args, **kwargs)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\addons\hr_biometric_machine\models\biometric_data_wizard.py", line 36, in crate_attendance_in_openep
biometric_machine, biometric_data_obj, biometric_user_obj,)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\addons\hr_biometric_machine\models\biometric_data.py", line 145, in import_data_classmethod
attendances = biometric_machine.getattendance()
File "C:\Python2.7.13\lib\site-packages\mock.py", line 1201, in patched
return func(*args, **keywargs)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\addons\hr_biometric_machine\models\biometric_machine.py", line 136, in getattendance
self.create_user()
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\api.py", line 266, in wrapper
return new_api(self, *args, **kwargs)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\addons\hr_biometric_machine\models\biometric_machine.py", line 119, in create_user
'biometric_device': self.id, }
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\api.py", line 266, in wrapper
return new_api(self, *args, **kwargs)
File "D:\odoo_8.0.20170129\odoo-8.0-20170129\openerp\addons\hr_biometric_machine\models\biometric_user.py", line 33, in create
userHasUserDevice = biometric_user_obj.search([('employee_id', '=', int(values['employee_id'])),
KeyError: 'employee_id'
biometric_user.py
class BiometricUser(models.Model):
_name = 'biometric.user'
biometric_id = fields.Integer('Id in biometric device')
name = fields.Char('Name in biometric device')
employee_id = fields.Many2one('hr.employee', 'Related employee')
biometric_device = fields.Many2one(
'biometric.machine', 'Biometric device', )
#api.model
def create(self, values):
userExist = None
biometric_machine_obj = self.env['biometric.machine']
biometric_user_obj = self.env['biometric.user']
userExist = biometric_user_obj.search([('biometric_id', '=', int(values['biometric_id'])),
('biometric_device', '=', int(values['biometric_device']))])
userHasUserDevice = biometric_user_obj.search([('employee_id', '=', int(values['employee_id'])),
('biometric_device', '=', int(values['biometric_device']))])
print(len(userExist))
if len(userExist) != 0:
raise Warning(_('User exist in ZK machine'))
else:
if len(userHasUserDevice) != 0:
raise Warning(_('Every employee doesn\'t have more than one user in a specific biometric device !'))
else:
openerp_machine = biometric_machine_obj.search([('id', '=', values['biometric_device']), ], )
print ("openerp_machine:", openerp_machine['ip_address'])
print ("biometric_device:", values['biometric_device'])
conn = None
zk = ZK(str(openerp_machine['ip_address']), port=int(openerp_machine['port']), timeout=5)
try:
print 'Connecting to device ...'
conn = zk.connect()
print 'Disabling device ...'
conn.disable_device()
conn.set_user(uid=int(str(values['biometric_id'])), name=str(values['name']),
privilege=const.USER_DEFAULT, password='', group_id='',
user_id=str(values['biometric_id']))
print 'Enabling device ...'
conn.enable_device()
res_id = super(BiometricUser, self).create(values)
except Exception, e:
print "Process terminate : {}".format(e)
raise Warning(_('Something bad happened. ' + str(e)))
finally:
if conn:
conn.disconnect()
return res_id
Please check values of create() method, employee_id is not available and you are trying to get employee_id from values.
You should check that employee_id is available in values or not as like following :
if 'employee_id' in values :
userHasUserDevice = biometric_user_obj.search([('employee_id', '=', int(values['employee_id'])),
('biometric_device', '=', int(values['biometric_device']))])
Related
I am trying to open the template sem.html and year.html from my project, but it is showing an error unnecessarily. Earlier it will open the template smoothly but when I m trying with the foreign key it is giving an error that str returned a non-string value. I am joining my models.py file code where I created two models named sem and year and in forms.py I have created two forms semforms and yearforms with two fields.
class subjects(models.Model):
subject_code = models.CharField(max_length=20,null=True)
subject_name = models.CharField(max_length=100,null=True)
subject_abv = models.CharField(max_length=10,null=True)
semester = models.IntegerField(null=True)
theory_load = models.IntegerField(null=True)
max_numb_students = models.CharField(max_length=65)
faculty = models.ManyToManyField(facultyload)
def __str__(self):
return self.subject_code,self.subject_name
class semester(models.Model):
sem_num = models.CharField(max_length=10,null=True)
sem_courses = models.ManyToManyField(subjects,related_name='sem_courses')
#property
def get_courses(self):
return self.sem_courses
def __str__(self):
return self.sem_num
class Year(models.Model):
year_name = models.CharField(max_length=50)
courses = models.ManyToManyField(subjects,related_name='courses')
#property
def get_courses(self):
return self.courses
def __str__(self):
return self.year_name
forms.py
class semforms(forms.ModelForm):
class Meta:
model = semester
fields = ['sem_num','sem_courses']
class yearforms(forms.ModelForm):
class Meta:
model = Year
fields = ['year_name','courses']
It is giving this error
TypeError at /sem/
__str__ returned non-string (type tuple)
Request Method: GET
Request URL: http://127.0.0.1:8000/sem/
Django Version: 3.1.4
Exception Type: TypeError
Exception Value:
__str__ returned non-string (type tuple)
Anyone can solve this, please help.
views.py - (same for year function, instead of sem I have taken year)
#login_required(login_url='login')
#allowed_users(allowed_roles=['admin','customer'])
def sem(request):
if request.method == 'POST':
form = semforms(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/sem')
except:
pass
else:
form = semforms()
sem = semester.objects.all()
total_sem = sem.count()
context = {'sem':sem,'total_sem':total_sem,'form':form}
return render(request,"sem.html",context)
#allowed_users(allowed_roles=['admin'])
def edit_sem(request, id):
sem = semester.objects.get(id=id)
return render(request,'editsem.html',{'sem':sem})
#allowed_users(allowed_roles=['admin'])
def update_sem(request, id):
sem = semester.objects.get(id=id)
form = semforms(request.POST,instance=sem)
if form.is_valid():
form.save()
messages.success(request,"Record updated successfully......")
return render(request,"editsem.html",{'sem':sem})
#allowed_users(allowed_roles=['admin'])
def delete_sem(request, id):
load = semester.objects.get(id=id)
load.delete()
return render(request,'sem.html',{'load':load})
Also, this is my full Traceback error.
Internal Server Error: /sem/
Traceback (most recent call last):
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Virti Parekh\projects\final\total_load\decorators.py", line 22, in wrapper_func
return view_func(request, *args, **kwargs)
File "C:\Users\Virti Parekh\projects\final\total_load\views.py", line 462, in sem
return render(request,"sem.html",context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\defaulttags.py", line 312, in render
return nodelist.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 988, in render
output = self.filter_expression.resolve(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 671, in resolve
obj = self.var.resolve(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 796, in resolve
value = self._resolve_lookup(context)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 858, in _resolve_lookup
current = current()
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\forms.py", line 297, in as_p
errors_on_separate_row=True,
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\forms.py", line 236, in _html_output
'field_name': bf.html_name,
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\html.py", line 376, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\boundfield.py", line 34, in __str__
return self.as_widget()
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\boundfield.py", line 97, in as_widget
renderer=self.form.renderer,
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\widgets.py", line 241, in render
context = self.get_context(name, value, attrs)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\widgets.py", line 678, in get_context
context = super().get_context(name, value, attrs)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\widgets.py", line 639, in get_context
context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\widgets.py", line 587, in optgroups
for index, (option_value, option_label) in enumerate(self.choices):
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 1157, in __iter__
yield self.choice(obj)
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 1171, in choice
self.field.label_from_instance(obj),
File "C:\Users\Virti Parekh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 1240, in label_from_instance
return str(obj)
TypeError: __str__ returned non-string (type tuple)
Change your subjects class __str__ method to this:
class subjects(models.Model):
def __str__(self):
return f"{self.subject_code},{self.subject_name}"
Overriding formfield_for_choice_field in inline admin throw key error even though i change nothing ?
ProfileInline:
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
classes = ['collapse', ]
form = ProfileForm
readonly_fields = ('thumbnail_img', )
extra = 1
max_num = 1
min_num = 1
fieldsets = (
(None, {
'fields': (
'thumbnail_img', 'avatar', 'nickname', 'gender',
'phone_number', 'birth_place', 'birth_date', 'angkatan',
'year_registered', 'year_graduation', 'religion', 'jobs'
)
}),
('Alamat saat sekolah di sman 3 Padang', {
'fields': ('old_address', )
}),
('Alamat sekarang', {
'fields': ('curr_country', 'curr_province',
'curr_city', 'curr_street')
}),
('Media Sosial', {
'fields': ('link_facebook', 'link_twitter', 'link_instagram',
'link_whatsup', 'link_bbm')
}),
('Sembunyikan Data Pribadi', {
'fields': ('show_phone', 'show_curr_address', 'show_jobs',
'show_social_link', 'show_family')
})
)
def formfield_for_choice_field(self, db_field, request, **kwargs):
super(ProfileInline, self).formfield_for_choice_field(db_field, request, **kwargs)
Key Error:
Traceback:
Internal Server Error: /admin/accounts/alumni/add/
Traceback (most recent call last):
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\forms\forms.py", line 144, in __getitem__
field = self.fields[name]
KeyError: 'gender'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
response = get_response(request)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response
response = response.render()
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\response.py", line 109, in render
self.content = self.rendered_content
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\response.py", line 86, in rendered_content
content = template.render(context, self._request)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\backends\django.py", line 66, in render
return self.template.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 208, in render
return self._render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 199, in _render
return self.nodelist.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 994, in render
bit = node.render_annotated(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\loader_tags.py", line 174, in render
return compiled_parent._render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 199, in _render
return self.nodelist.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 994, in render
bit = node.render_annotated(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\loader_tags.py", line 174, in render
return compiled_parent._render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 199, in _render
return self.nodelist.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 994, in render
bit = node.render_annotated(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\loader_tags.py", line 70, in render
result = block.nodelist.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 994, in render
bit = node.render_annotated(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\loader_tags.py", line 70, in render
result = block.nodelist.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 994, in render
bit = node.render_annotated(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\defaulttags.py", line 209, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\loader_tags.py", line 210, in render
return template.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 210, in render
return self._render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 199, in _render
return self.nodelist.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 994, in render
bit = node.render_annotated(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\defaulttags.py", line 209, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\defaulttags.py", line 209, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\loader_tags.py", line 210, in render
return template.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 210, in render
return self._render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 199, in _render
return self.nodelist.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 994, in render
bit = node.render_annotated(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\defaulttags.py", line 209, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\base.py", line 961, in render_annotated
return self.render(context)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\template\defaulttags.py", line 165, in render
values = list(values)
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\contrib\admin\helpers.py", line 115, in __iter__
yield AdminField(self.form, field, is_first=(i == 0))
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\contrib\admin\helpers.py", line 127, in __init__
self.field = form[field] # A django.forms.BoundField instance
File "C:\Users\afdallismen\Envs\ikasmantri\lib\site-packages\django\forms\forms.py", line 150, in __getitem__
', '.join(sorted(f for f in self.fields)),
KeyError: "Key 'gender' not found in 'ProfileForm'. Choices are: avatar, birth_date, birth_place, curr_city, curr_country, curr_province, curr_street, id, jobs, link_bbm, link_facebook, link_instagram, link_twitter, link_whatsup, nickname,
old_address, phone_number, show_curr_address, show_family, show_jobs, show_phone, show_social_link, user."
[11/Apr/2017 23:52:29] "GET /admin/accounts/alumni/add/ HTTP/1.1" 500 381609
ProfileForm:
class ProfileForm(forms.ModelForm):
curr_street = Address._meta.get_field('street').formfield()
curr_city = Address._meta.get_field('city').formfield()
curr_province = Address._meta.get_field('province').formfield()
curr_country = Address._meta.get_field('country').formfield()
class Meta:
model = Profile
fields = '__all__'
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
self.fields['birth_date'].input_formats = settings.DATE_INPUT_FORMATS
if self.instance.pk is not None:
self.fields['curr_street'].initial = self.instance.address.street
self.fields['curr_city'].initial = self.instance.address.city
self.fields[
'curr_province'].initial = self.instance.address.province
self.fields['curr_country'].initial = self.instance.address.country
self.helper = FormHelper()
self.helper.form_tag = False
I tried to remove fieldset from inline, and it does not throw any error. Is fieldsets the cause here ?
Looking back at traceback, i found that the key that was not found are fields that using choices.
Here is subset of my model:
class Profile(models.Model):
GENDER_CHOICES = choices.GENDER_CHOICES
RELIGION_CHOICES = choices.RELIGION_CHOICES
ANGKATAN_CHOICES = choices.ANGKATAN_CHOICES
YEAR_REGISTERED_CHOICES = choices.YEAR_REGISTERED_CHOICES
YEAR_GRADUATION_CHOICES = choices.YEAR_GRADUATION_CHOICES
gender = models.CharField(
verbose_name="jenis kelamin",
max_length=1,
choices=GENDER_CHOICES
)
angkatan = models.PositiveIntegerField(
verbose_name="angkatan",
choices=ANGKATAN_CHOICES,
help_text="Angkatan di Sman 3 Padang."
)
year_registered = models.PositiveIntegerField(
verbose_name="tahun masuk",
choices=YEAR_REGISTERED_CHOICES,
help_text="Tahun masuk di Sman 3 Padang."
)
year_graduation = models.PositiveIntegerField(
verbose_name="tahun lulus",
choices=YEAR_GRADUATION_CHOICES,
help_text="Tahun lulus dari Sman 3 Padang."
)
religion = models.PositiveIntegerField(
verbose_name="agama",
choices=RELIGION_CHOICES
)
Those 5 fields are not found in ProfileForm.
Found sort of hacks for this, by not calling super in formfield_for_choice_field and using base implementation found in django.contrib.admin.options.BaseModelAdmin class:
def formfield_for_choice_field(self, db_field, request, **kwargs):
# super(ProfileInline, self).formfield_for_choice_field(db_field, request, **kwargs)
if db_field.name == "angkatan" and not request.user.is_superuser:
kwargs['choices'] = (
(request.user.admin.angkatan, str(request.user.admin.angkatan)),
)
# Base implementation bellow
if db_field.name in self.radio_fields:
# Avoid stomping on custom widget/choices arguments.
if 'widget' not in kwargs:
kwargs['widget'] = widgets.AdminRadioSelect(attrs={
'class': get_ul_class(self.radio_fields[db_field.name]),
})
if 'choices' not in kwargs:
kwargs['choices'] = db_field.get_choices(
include_blank=db_field.blank,
blank_choice=[('', _('None'))]
)
return db_field.formfield(**kwargs)
The formfield_for_choice_field override should return something. You should write it this way:
def formfield_for_choice_field(self, db_field, request, **kwargs):
if db_field.name == "some_field":
# do stuff
return super(ProfileInline, self).formfield_for_choice_field(db_field, request, **kwargs)
You should aware, also the note below the formfield_for_choice_field explanation. This is explained in detail here.
Please help me understand :
With that code, the file is stored and everything goes well :
uploaded_file = request.FILES['file']
file_name = str(uploaded_file.name)
print ("filename = ", file_name)
#project_name = extract_project_name(uploaded_file)
#print ("project name = ", project_name)
found_entries = Project.objects.filter(name=file_name)
if(found_entries.count() == 0):
project = Project()
project.create(
file=uploaded_file,
)
But if I uncomment, I have an error to re extract data when creating the object in the database, because it is None ...
Any Idea ?
Traceback :
Traceback (most recent call last):
File "<some path>/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "<some path>/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "<path here>/views.py", line 101, in upload_project_file
file=uploaded_file,
File "<path here>/project.py", line 33, in create
project.extract_project_infos()
File "<path here>/project.py", line 40, in extract_project_infos
Project_Data = json.loads(data)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I was trying to use functions from old api to new api:
#api.multi
def search(self, *args, **kwargs):
offset = kwargs.get("offset", 0)
limit = kwargs.get("limit", None)
order = kwargs.get("order", 'complete_name')
context = kwargs.get("context", None)
count = kwargs.get("count", False)
for index, expr in enumerate(args):
if expr[1] in ['like', 'ilike', 'not ilike', 'not like', '=like']:
args[index][2] = re.sub(r"\s+", '%', expr[2])
return super(stock_location, self).search(*args, **kwargs)
and
def name_search(self, cr, uid, name='', args=None, operator='ilike', context=None, limit=80):
args.append(['complete_name', operator, name])
ids = self.search(cr, uid, args, limit=limit, context=context)
return self.name_get(cr, uid, ids)
I got error.
Odoo Server Error
Traceback (most recent call last):
File "/opt/odoo/openerp/http.py", line 643, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/opt/odoo/openerp/http.py", line 680, in dispatch
result = self._call_function(**self.params)
File "/opt/odoo/openerp/http.py", line 316, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/opt/odoo/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "/opt/odoo/openerp/http.py", line 309, in checked_call
result = self.endpoint(*a, **kw)
File "/opt/odoo/openerp/http.py", line 959, in __call__
return self.method(*args, **kw)
File "/opt/odoo/openerp/http.py", line 509, in response_wrap
response = f(*args, **kw)
File "/opt/odoo/addons/web/controllers/main.py", line 892, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/opt/odoo/addons/web/controllers/main.py", line 884, in _call_kw
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "/opt/odoo/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/opt/odoo/openerp/api.py", line 381, in old_api
result = method(recs, *args, **kwargs)
File "/opt/odoo/openerp/models.py", line 6053, in onchange
record._onchange_eval(name, field_onchange[name], result)
File "/opt/odoo/openerp/models.py", line 5910, in _onchange_eval
method_res = method(self)
File "/home/del/addons/mik_stock/wizard/stock_operation.py", line 193, in onchange_picking_type
if self.env['stock.location'].search_count(domain_from) == 1:
File "/opt/odoo/openerp/api.py", line 248, in wrapper
return new_api(self, *args, **kwargs)
File "/opt/odoo/openerp/api.py", line 490, in new_api
result = method(self._model, cr, uid, *args, **old_kwargs)
File "/opt/odoo/openerp/models.py", line 1634, in search_count
res = self.search(cr, user, args, context=context, count=True)
File "/opt/odoo/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/opt/odoo/openerp/api.py", line 380, in old_api
recs = self.browse(cr, uid, ids, context)
File "/opt/odoo/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/opt/odoo/openerp/models.py", line 5361, in browse
return self._browse(Environment(cr, uid, context or {}), ids)
File "/opt/odoo/openerp/models.py", line 5354, in _browse
env.prefetch[cls._name].update(ids)
TypeError: unhashable type: 'list'
When I use only search function with decorator #api.multi everything seems ok. So maybe this error because of name_search function? Do I have decorate this function and cr, uid, ids change to self.env?
You are not passing your domain (search conditions) properly.
Your args should contain List of tuples,
like
[('phone','=','1122445566'),('id','!=',self.id)]
In short,
[(field, operator, value)]
I want to import data from a csv file to a model. So I have this code which does the job for me:
Import.py
import csv
with open('usuarios.csv') as f:
reader = csv.reader(f)
for row in reader:
created = Users.objects.create(
field1=row[0],
field2=row[1],
field3=row[2],
)
And my model:
class Users(AbstractBaseUser):
field1 = models.CharField(max_length=100, null=True)
field2 = models.CharField(max_length=100, null=True)
field3 = models.CharField(max_length=100, null=True)
But for some reason, when I execute import.ty the console handles this:
File "<console>", line 1, in <module>
File "<string>", line 25, in <module>
File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 154, in
get_or_create
return self.get_queryset().get_or_create(**kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 376, in g
et_or_create
return self.get(**lookup), False
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 301, in g
et
clone = self.filter(*args, **kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 593, in f
ilter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\db\models\query.py", line 611, in _
filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Python34\lib\site-packages\django\db\models\sql\query.py", line 1204,
in add_q
clause = self._add_q(where_part, used_aliases)
File "C:\Python34\lib\site-packages\django\db\models\sql\query.py", line 1240,
in _add_q
current_negated=current_negated)
File "C:\Python34\lib\site-packages\django\db\models\sql\query.py", line 1131,
in build_filter
clause.add(constraint, AND)
File "C:\Python34\lib\site-packages\django\utils\tree.py", line 104, in add
data = self._prepare_data(data)
File "C:\Python34\lib\site-packages\django\db\models\sql\where.py", line 79, i
n _prepare_data
value = obj.prepare(lookup_type, value)
File "C:\Python34\lib\site-packages\django\db\models\sql\where.py", line 352,
in prepare
return self.field.get_prep_lookup(lookup_type, value)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line
1085, in get_prep_lookup
return super(IntegerField, self).get_prep_lookup(lookup_type, value)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line
369, in get_prep_lookup
return self.get_prep_value(value)
File "C:\Python34\lib\site-packages\django\db\models\fields\__init__.py", line
1079, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: '(3482) 453874'
Ideas ? I've been reading that it could have something to be with the primary_key, but I dont know what exactly
Try this:
import csv
with open('usuarios.csv') as f:
reader = csv.reader(f)
for row in reader:
kwargs = {field1=row[0],
field2=row[1],
field3=row[2],}
created = Users(**kwargs)
created.save()