Related
In my application I have 2 models:
class Employee(models.Model):
first_name = models.CharField(max_length=100, null=False)
last_name = models.CharField(max_length=100, null=False)
email_id = models.EmailField(null=False)
class UserGroup(models.Model):
created_by = models.EmailField(null=False)
An UserGroup can be created by an Employee or by the "System". So, the possible values for "created_by" are:
"employeex#mail.com"
"System"
Now, I want to expose this property in graphql. From the graphql, I want to be able to get the properties of created_by (like firstName, lastName etc) if created_by is an Employee. Otherwise I want to get String in the graphql response.
Here is what I have done so far:
import graphene
from graphene_django.types import DjangoObjectType
from models import Employee, UserGroup
class EmployeeObjectType(DjangoObjectType):
class Meta:
model = Employee
class UserGroupCreatedBy(graphene.Union):
class Meta:
types = (EmployeeObjectType, graphene.String, )
class UserGroupType(DjangoObjectType):
created_by = graphene.Field(UserGroupCreatedBy)
def resolve_created_by(self, info):
if self.created_by == "System":
return self.created_by
return Employee.objects.get(email_id=self.created_by)
class Meta:
model = UserGroup
query {
userGroups {
createdBy {
... on EmployeeType {
firstName
}
}
}
}
When I request the graphql API, this is the error that I am getting:
ERROR:django.request:Internal Server Error: /graphql
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 113, in __call__
response = self.process_request(request)
File "/usr/local/lib/python3.9/site-packages/django/middleware/common.py", line 53, in process_request
if self.should_redirect_with_slash(request):
File "/usr/local/lib/python3.9/site-packages/django/middleware/common.py", line 71, in should_redirect_with_slash
not is_valid_path(request.path_info, urlconf) and
File "/usr/local/lib/python3.9/site-packages/django/urls/base.py", line 154, in is_valid_path
resolve(path, urlconf)
File "/usr/local/lib/python3.9/site-packages/django/urls/base.py", line 25, in resolve
return get_resolver(urlconf).resolve(path)
File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 549, in resolve
for pattern in self.url_patterns:
File "/usr/local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 593, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 586, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/code/project_name/urls.py", line 34, in <module>
from spm.graphql.data_loaders import (
File "/code/spm/graphql/__init__.py", line 1, in <module>
from .schema import *
File "/code/spm/graphql/schema.py", line 102, in <module>
schema = graphene.Schema(query=Query, mutation=Mutation)
File "/usr/local/lib/python3.9/site-packages/graphene/types/schema.py", line 78, in __init__
self.build_typemap()
File "/usr/local/lib/python3.9/site-packages/graphene/types/schema.py", line 167, in build_typemap
self._type_map = TypeMap(
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 80, in __init__
super(TypeMap, self).__init__(types)
File "/usr/local/lib/python3.9/site-packages/graphql/type/typemap.py", line 31, in __init__
self.update(reduce(self.reducer, types, OrderedDict())) # type: ignore
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 88, in reducer
return self.graphene_reducer(map, type)
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 117, in graphene_reducer
return GraphQLTypeMap.reducer(map, internal_type)
File "/usr/local/lib/python3.9/site-packages/graphql/type/typemap.py", line 109, in reducer
field_map = type_.fields
File "/usr/local/lib/python3.9/site-packages/graphql/pyutils/cached_property.py", line 22, in __get__
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "/usr/local/lib/python3.9/site-packages/graphql/type/definition.py", line 198, in fields
return define_field_map(self, self._fields)
File "/usr/local/lib/python3.9/site-packages/graphql/type/definition.py", line 212, in define_field_map
field_map = field_map()
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 275, in construct_fields_for_type
map = self.reducer(map, field.type)
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 88, in reducer
return self.graphene_reducer(map, type)
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 93, in graphene_reducer
return self.reducer(map, type.of_type)
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 88, in reducer
return self.graphene_reducer(map, type)
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 117, in graphene_reducer
return GraphQLTypeMap.reducer(map, internal_type)
File "/usr/local/lib/python3.9/site-packages/graphql/type/typemap.py", line 109, in reducer
field_map = type_.fields
File "/usr/local/lib/python3.9/site-packages/graphql/pyutils/cached_property.py", line 22, in __get__
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "/usr/local/lib/python3.9/site-packages/graphql/type/definition.py", line 198, in fields
return define_field_map(self, self._fields)
File "/usr/local/lib/python3.9/site-packages/graphql/type/definition.py", line 212, in define_field_map
field_map = field_map()
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 275, in construct_fields_for_type
map = self.reducer(map, field.type)
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 88, in reducer
return self.graphene_reducer(map, type)
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 117, in graphene_reducer
return GraphQLTypeMap.reducer(map, internal_type)
File "/usr/local/lib/python3.9/site-packages/graphql/type/typemap.py", line 99, in reducer
for t in type_.types:
File "/usr/local/lib/python3.9/site-packages/graphql/pyutils/cached_property.py", line 22, in __get__
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "/usr/local/lib/python3.9/site-packages/graphql/type/definition.py", line 429, in types
return define_types(self, self._types)
File "/usr/local/lib/python3.9/site-packages/graphql/type/definition.py", line 440, in define_types
types = types()
File "/usr/local/lib/python3.9/site-packages/graphene/types/typemap.py", line 251, in types
assert internal_type.graphene_type == objecttype
AttributeError: 'GraphQLScalarType' object has no attribute 'graphene_type'
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}"
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']))])
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.
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)]