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'
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)
Lets say we have a list that is comprised of a range of numbers:
list_1 = [] # all numbers between a range
for num in range(0,1000):
if num > 0:
list_1.append(num)
Now we want to seperate some numbers from this list, for example, primes:
list_2 = [] # all prime numbers in list_1
for num in list_1:
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
list_2.append(num)
Now we want to seperate the list even further, and we notice that prime numbers end in either a 1, 3, 7, or 9. So we tell our program to seperate the primes that end in a certain digit:
list_3 = [] # all prime numbers in list_1 that end in the last digit 1
list_4 = [] # all prime numbers in list_1 that end in the last digit 3
list_5 = [] # all prime numbers in list_1 that end in the last digit 7
list_6 = [] # all prime numbers in list_1 that end in the last digit 9
for num in list_2:
lastdigit = int(repr(num)[-1])
if lastdigit == 1:
list_3.append(num)
elif lastdigit == 3:
list_4.append(num)
elif lastdigit == 7:
list_5.append(num)
elif lastdigit == 9:
list_6.append(num)
What we want to do is to define a function that compares the elements of list_2 with list_3 through list_6. The purpose would be to create uniquely named lists that group the primes from list_2 into list that begin and end with groups of the same digit. For instance if we run the code we see:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
We can see on this list that there are prime numbers that end in the same digit and have another number ending in the same digit for instance 181, 191.
If we look at the list further down we can see another instance where 241, 251.
What we want our list to look like is:
list1_1 = [181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251]
And we want to do this for all numbers in our list of primes. How do we go about doing that? I'm new to python and just trying to understand how to manipulate variables and lists and to compare information between lists for the purpose of computation in number theory. Thanks for your help.
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()