How to compare elements in multiple lists - list

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.

Related

Django graphene - Unable to query union field

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'

tensorflowr1.2 translate.py AttributeError: 'NoneType' object has no attribute 'update'

I am now using twensorflow to implement nmt. When I run the tensorflow case, the following problems arise.I use tensorflow1.2.
The problem is shown in fllow.
Creating 3 layers of 1024 units.
Traceback (most recent call last):
File "translate.py", line 322, in <module>
tf.app.run()
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "translate.py", line 319, in main
train()
File "translate.py", line 178, in train
model = create_model(sess, False)
File "translate.py", line 136, in create_model dtype=dtype)
File "/home/kings/models/tutorials/rnn/translate/seq2seq_model.py", line 179, in __init__ softmax_loss_function=softmax_loss_function)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 1206, in model_with_buckets
decoder_inputs[:bucket[1]])
File "/home/kings/models/tutorials/rnn/translate/seq2seq_model.py", line 178, in <lambda>lambda x, y: seq2seq_f(x, y, False),
File "/home/kings/models/tutorials/rnn/translate/seq2seq_model.py", line 142, in seq2seq_f
dtype=dtype)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py", line 848, in embedding_attention_seq2seq encoder_cell = copy.deepcopy(cell)
File "/usr/lib/python2.7/copy.py", line 174, in deepcopy y = copier(memo)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/layers/base.py", line 476, in __deepcopy__ setattr(result, k, copy.deepcopy(v, memo))
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 230, in _deepcopy_list
y.append(deepcopy(a, memo))
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 230, in _deepcopy_list
y.append(deepcopy(a, memo))
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 230, in _deepcopy_list
y.append(deepcopy(a, memo))
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 237, in _deepcopy_tuple
y.append(deepcopy(a, memo))
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 334, in _reconstruct
state = deepcopy(state, memo)
File "/usr/lib/python2.7/copy.py", line 163, in deepcopy
y = copier(x, memo)
File "/usr/lib/python2.7/copy.py", line 257, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File "/usr/lib/python2.7/copy.py", line 190, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.7/copy.py", line 343, in _reconstruct
y.__dict__.update(state)
AttributeError: 'NoneType' object has no attribute 'update'
Source code such as website link: https://github.com/tensorflow/models/tree/master/tutorials/rnn/translate
I just started learning and was in desperate need of your help. Thank you in advance.

Overriding formfield_for_choice_field throw key error

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.

Django AttributeError: 'datetime.date' object has no attribute 'date'

I'm trying to make a calendar template tag I found online work, but it's balking at using dates. I'm not sure, and datetime is just really confusing to me. Sometimes it works and I have no idea why, and sometimes it doesn't work, and I have no idea why.
My model:
class Event(models.Model):
unique_id = models.IntegerField(default=1)
subject = models.CharField(max_length=140, blank=True, null=True)
body = models.TextField(null=True, blank=True)
start_date = models.DateField(null=True, blank=True)
start_time = models.TimeField(null=True, blank=True)
end_date = models.DateField(null=True, blank=True)
end_time = models.TimeField(null=True, blank=True)
and the offending code in the template tag:
from django import template
from datetime import date, timedelta
from cal.models import Event
def cal_month(year=date.today().year, month=date.today().month):
event_list = Event.objects.filter(start_date__year=year, start_date__month=month)
first_day_of_month = date(year, month, 1)
last_day_of_month = get_last_day_of_month(year, month)
first_day_of_calendar = first_day_of_month - timedelta(first_day_of_month.weekday()+1)
last_day_of_calendar = last_day_of_month + timedelta(7 - last_day_of_month.weekday())
cal_month = []
week = []
week_headers = []
i = 0
day = first_day_of_calendar
while day <= last_day_of_calendar:
if i < 7:
week_headers.append(day)
cal_day = {}
cal_day['day'] = day
cal_day['event'] = False
for event in event_list:
if day >= event.start_date.date() and day <= event.end_date.date():
cal_day['event'] = True
if day.month == month:
cal_day['in_month'] = True
else:
cal_day['in_month'] = False
week.append(cal_day)
if day.weekday() == 5:
cal_month.append(week)
week = []
i += 1
day += timedelta(1)
return {'calendar': cal_month, 'headers': week_headers}
register.inclusion_tag('calendar.html')(cal_month)
it's this line:
if day >= event.start_date.date() and day <= event.end_date.date():
that keeps failing. I can't understand why. It's a regular DateField. How do I tell Django to see it as a date?
Here is the maximum recursion error I get when I try to change the line to: "if day >= event.start_date and day <= event.end_date:"
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/webapps/programgr/cal/views.py", line 37, in view_calendar
return render(request, 'calendar.html', args)
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py", line 67, in render
template_name, context, request=request, using=using)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 99, in render_to_string
return template.render(context, request)
File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py", line 74, in render
return self.template.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 209, in render
return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 201, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 135, in render
return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 201, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 65, in render
result = block.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 1292, in render
return t.render(new_context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 211, in render
return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 201, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 135, in render
return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 201, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 65, in render
result = block.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 1292, in render
return t.render(new_context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 211, in render
return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 201, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 135, in render
return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 201, in _render
return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 903, in render
bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 917, in render_node
return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 65, in render
result = block.nodelist.render(context)
This just loops until the end of the log where it says "Maximum recursion error."

Django invalid literal for int() with base 10:

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()