'User' object has no attribute '__getitem__' error - django

I have the following model:
class StudentUsername(models.Model):
user = models.OneToOneField(User)
student = models.ForeignKey(Student)
When I try to add a user and student to this table using default Django Admin interface, I get the following error:
Exception Type: TypeError
Exception Value: 'User' object has no attribute '__getitem__'
Kindly help.
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
432. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
198. return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
25. return func(self, *args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\db\transaction.py" in inner
371. return func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in add_view
1133. self.log_addition(request, new_object)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in log_addition
600. action_flag=ADDITION
File "C:\Python27\lib\site-packages\django\contrib\admin\models.py" in log_action
19. e = self.model(None, None, user_id, content_type_id, smart_text(object_id), object_repr[:200], action_flag, change_message)
Exception Type: TypeError at /backoffice/students/studentusername/add/
Exception Value: 'User' object has no attribute '__getitem__'

It seems likely that you have defined a __unicode__ method on StudentUsername that is returning either a User or a Student object - that is, self.user or self.student - rather than actual unicode. So when Django tries to slice it, it gets this error.
Ensure that your unicode method actually returns unicode text.

Related

Django - The 'image' attribute has no file associated with it

User can register without a profile image.
Now I get error that no file was associated with the login.
Why does it validate the form and then try to save the image?
It should not check for the image.
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/views.py" in dispatch
90. return super(LoginView, self).dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py" in post
183. return self.form_valid(form)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/views.py" in form_valid
119. auth_login(self.request, form.get_user())
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/__init__.py" in login
161. user_logged_in.send(sender=user.__class__, request=request, user=user)
File "/usr/local/lib/python2.7/dist-packages/django/dispatch/dispatcher.py" in send
193. for receiver in self._live_receivers(sender)
File "/home/django/django_project/accounts/views.py" in got_online
115. user.profile.save()
File "/home/django/django_project/accounts/models.py" in save
116. img = Image.open(self.image.path)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in path
64. self._require_file()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in _require_file
46. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
Exception Type: ValueError at /login/
Exception Value: The 'image' attribute has no file associated with it.
accounts/models.py
class UserProfile(models.Model):
image = models.ImageField(upload_to=upload_image_path,null=True,blank=True)
def save(self, *args, **kwargs):
super(UserProfile,self).save(*args, **kwargs)
if self.image != None:
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
def post_save_user_receiver(sender, instance, created, *args, **kwargs):
if created:
new_profile = UserProfile.objects.get_or_create(user=instance)
The registration works without the user having a image, but the login does not.
Thank you for any help
I solved it by adding a default image to the file field:
image = models.ImageField(upload_to=upload_image_path,default='default.jpeg')
and by changing the if statement in the save method
from:
if self.image != None:
to:
if not self.image:
According to traceback, there is a signal receiver in accounts/views.py#115, that listens for user_logged_in signal and tries to save user profile:
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/__init__.py" in login
161. user_logged_in.send(sender=user.__class__, request=request, user=user)
...
File "/home/django/django_project/accounts/views.py" in got_online
115. user.profile.save()
And in user profile save and tries to open the profile image to thumbnail it.

Django Admin - 'bool' object is not callable

When I try and delete records within Django Admin, for some records, I am getting
'bool' object is not callable
I cannot work out where the error is based on this Traceback.
Traceback:
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper
575. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
62. return bound_func(*args, **kwargs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
58. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/options.py" in delete_view
1736. return self._delete_view(request, object_id, extra_context)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/options.py" in _delete_view
1760. [obj], opts, request.user, self.admin_site, using)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/utils.py" in get_deleted_objects
131. collector.collect(objs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/utils.py" in collect
195. return super().collect(objs, source_attr=source_attr, **kwargs)
File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/db/models/deletion.py" in collect
222. field.remote_field.on_delete(self, field, sub_objs, self.using)
Exception Type: TypeError at /admin/jobboard/job/155/delete/
Exception Value: 'bool' object is not callable
Can anyone suggest where to look? Thank you
You have set an on_delete of a ForeignKey, or OneToOneField to a boolean (True or False). So something like:
class SomeModel(models.Model):
some_fk = models.ForeignKey(OtherModel, on_delete=False)
You can not set this to a boolean. You can set this to the values listed in the documentation: CASCADE, PROTECT, SET_NULL, SET_DEFAULT, SET(..), or DO_NOTHING.
You could, strictly speaking, implement your own strategy as well, since the ones listed above are in fact just functions. For example the CASCADE is implemented like [GitHub]:
def CASCADE(collector, field, sub_objs, using):
collector.collect(sub_objs, source=field.remote_field.model,
source_attr=field.name, nullable=field.null)
if field.null and not connections[using].features.can_defer_constraint_checks:
collector.add_field_update(field, None, sub_objs)
although likely you do not need to implement your own, and pick one of the ones listed in the documentation. For example:
class SomeModel(models.Model):
some_fk = models.ForeignKey(OtherModel, on_delete=models.CASCADE)

"Unsafe redirect to URL with protocol 'content-type'" error in Django view

I'm having this problem with this use of the get_success_url() in my CreateView class:
def get_success_url(self):
search = searchViews.getIndexInstance()
search.mainfunc(self.contentForSearch, self.discussion.pk)
return HttpResponseRedirect(reverse('discussion-detail', kwargs={'slug':self.discussion.slug}))
Here's the complete error stacktrace:
Traceback:
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
34. return bound_func(*args, **kwargs)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
30. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/nithin/djangopro/viewanalyse/discussion/views.py" in dispatch
30. return super(LoggedInMixin, self).dispatch(*args, **kwargs)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
249. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
215. return self.form_valid(form)
File "/home/nithin/djangopro/viewanalyse/discussion/views.py" in form_valid
374. return super(DiscussionContentUpdateCreateView, self).form_valid(form)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/views/generic/edit.py" in form_valid
194. return super(ModelFormMixin, self).form_valid(form)
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/views/generic/edit.py" in form_valid
108. return HttpResponseRedirect(self.get_success_url())
File "/home/nithin/djangopro/djangoenv/local/lib/python2.7/site-packages/django/http/response.py" in __init__
456. raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
Exception Type: DisallowedRedirect at /discussion/discussion-content-update/why-i-believe-in-reincarnation-g-hijo-2015-08-09-162236316999/
Exception Value: Unsafe redirect to URL with protocol 'content-type'
What's the cause and how can I fix this?
The get_success_url method should return a URL, not an HTTP response.
def get_success_url(self):
search = searchViews.getIndexInstance()
search.mainfunc(self.contentForSearch, self.discussion.pk)
return reverse('discussion-detail',kwargs={'slug':self.discussion.slug})
It's not clear what the first two lines are for, they don't seem to be used by the reverse() call.

Redefining class attributes in derived model classes, Django

I want to redefine class attribute in derived class. The email attribute is already exists in parent class User, but it's have no unique=True property as I need. I know that Django does not support this feature directly. So I did that:
class CustomUser(User):
"""The inherited User class. Email field are redefined to add the warning
about uniqueness is required. UserManager as the default manager so that
the standard methods are available."""
def __init__(self, *args, **kwargs):
super(CustomUser, self).__init__(*args, **kwargs)
email = models.EmailField(unique=True)
email.contribute_to_class(u'email', self)
objects = UserManager()
Traceback:
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/admin/options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/admin/sites.py" in inner
196. return self.login(request)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/admin/sites.py" in login
331. return login(request, **defaults)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/auth/views.py" in login
35. if form.is_valid():
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/forms/forms.py" in is_valid
121. return self.is_bound and not bool(self.errors)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/forms/forms.py" in _get_errors
112. self.full_clean()
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/forms/forms.py" in full_clean
268. self._clean_form()
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/forms/forms.py" in _clean_form
296. self.cleaned_data = self.clean()
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/admin/forms.py" in clean
26. self.user_cache = authenticate(username=username, password=password)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/contrib/auth/__init__.py" in authenticate
55. user = backend.authenticate(**credentials)
File "/home/i159/workspace/students/backends.py" in authenticate
15. print self.user_class()
File "/home/i159/workspace/students/stdapp/models.py" in __init__
13. email.contribute_to_class(u'email', self)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/db/models/fields/__init__.py" in contribute_to_class
235. self.set_attributes_from_name(name)
File "/home/i159/Envs/students/lib/python2.6/site-packages/django/db/models/fields/__init__.py" in set_attributes_from_name
232. self.verbose_name = name.replace('_', ' ')
Exception Type: AttributeError at /admin/stdapp/customuser/add/
Exception Value: 'CustomUser' object has no attribute 'replace'
What can I do to fix it or how to set unique to True in email field? What the cause of this exception?
Edit:
Another way to do this.
First variation:
class CustomUser(User):
def __init__(self, *args, **kwargs):
setattr(self._meta.fields[4], 'unique', True)
Second:
class CustomUser(User):
def __init__(self, *args, **kwargs):
self._meta.fields[4].unique=True
Both are have the same error: can't set attribute.

Django admin 'save_as' with inlines

Should 'save_as' work with inlines. I'm rather baffled by the traceback but it doesn't seem to show much involvement of my own code.
The problem seems to be the id's of inlines being set to '' when saving an add form. This is handled quite happily by when you do a normal 'add':
Traceback:
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
197. return view(request, *args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
28. return bound_func(*args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
24. return func(self, *args2, **kwargs2)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/db/transaction.py" in inner
217. res = func(*args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
879. prefix=prefix, queryset=inline.queryset(request))
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/forms/models.py" in __init__
682. queryset=qs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/forms/models.py" in __init__
415. super(BaseModelFormSet, self).__init__(**defaults)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/forms/formsets.py" in __init__
47. self._construct_forms()
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/forms/formsets.py" in _construct_forms
108. self.forms.append(self._construct_form(i))
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
691. form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
437. connection=connections[self.get_queryset().db])
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/db/models/fields/subclassing.py" in inner
53. return func(*args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/db/models/fields/subclassing.py" in inner
53. return func(*args, **kwargs)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_lookup
306. value = self.get_prep_lookup(lookup_type, value)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
292. return self.get_prep_value(value)
File "/Users/andybaker/.virtualenvs/nmdc_test/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
479. return int(value)
Exception Type: ValueError at /admin/property_manager/property/add/
Exception Value: invalid literal for int() with base 10: ''
Could be related to this if you're using FileFields? https://code.djangoproject.com/ticket/14760