'用户'对象没有属性' __ getitem __'错误

时间:2014-06-16 11:57:36

标签: django

我有以下型号:

class StudentUsername(models.Model):
    user = models.OneToOneField(User)
    student = models.ForeignKey(Student)

当我尝试使用默认的Django Admin界面将用户和学生添加到此表时,出现以下错误:

Exception Type: TypeError
Exception Value: 'User' object has no attribute '__getitem__'

请帮助。

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__'

1 个答案:

答案 0 :(得分:2)

您可能在StudentUsername上定义了一个返回User或Student对象的__unicode__方法 - 即self.userself.student - 而不是实际的unicode。因此,当Django尝试对其进行切片时,会出现此错误。

确保您的unicode方法实际返回unicode文本。