странная ошибка django-avatar

#python #django

#python #django

Вопрос:

Я использую django-avatar, и мой шаблон имеет:

 {% load i18n avatar_tags %}
{% render_avatar avatar 100 %}
  

и я получаю эту ошибку:

 Environment:


Request Method: GET
Request URL: http://test.me/profile/myuser

Django Version: 1.3
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'test',
 'avatar']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.csrf.CsrfResponseMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Template error:
In template /srv/www/test.me/localhost/test/templates/profile.html, error at line 23
   Caught VariableDoesNotExist while rendering: Failed lookup for key [avatar] in u'[{}, {'csrf_token': <django.utils.functional.__proxy__ object at 0xb93445ac>}, {'perms': <django.utils.functional.__proxy__ object at 0xb9344cec>, 'messages': <django.contrib.messages.storage.user_messages.LegacyFallbackStorage object at 0xb936258c>, 'user': <django.utils.functional.SimpleLazyObject object at 0xb9344bcc>}, {}, {'LANGUAGES': (('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese')), 'LANGUAGE_BIDI': False, 'LANGUAGE_CODE': 'en-us'}, {'MEDIA_URL': 'http://test.me/media/'}, {'STATIC_URL': '/static/'}, {'messages': <django.contrib.messages.storage.user_messages.LegacyFallbackStorage object at 0xb936258c>}, {'messages': [], 'user': <User: myuser>, 'form': <localhost.test.forms.messagesForm object at 0xb936270c>, 'unread_messages': []}, {'block': <Block Node: content. Contents: [<Text Node: 'n<center>n    '>, <If node>, <Text Node: 'n    n<h2>Describe '>, <Variable Node: user.username>, <Text Node: ' in three messages!</h2>nn<d'>, <django.template.base.SimpleNode object at 0xb937772c>, <Text Node: 'n</div>nn<form id="messages_'>, <Variable Node: user.id>, <Text Node: '" id="id_user" /></li> n '>, <If node>, <Text Node: 'n<input type="submit" val'>, <If node>, <Text Node: 'nn'>]>}]'
   13 :     <ul class="messages" style="display: none">


   14 :         {% for message in messages %}


   15 :         <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>


   16 :         {% endfor %}


   17 :     </ul>


   18 :     {% endif %}


   19 :     


   20 : <h2>Describe {{ user.username }} in three messages!</h2>


   21 : 


   22 : <div id="avatar_box">


   23 :      {% render_avatar avatar 100 %} 


   24 : </div>


   25 : 


   26 : <form id="messages_form" action="" method="post">


   27 :     <ul> 


   28 :     <li><input type="text" name="message_1" id="id_message_1" /></li> 


   29 :     <li><input type="text" name="message_2" id="id_message_2" /></li> 


   30 :     <li><input type="text" name="message_3" id="id_message_3" />


   31 :         <input type="hidden" name="user" value="{{user.id}}" id="id_user" /></li> 


   32 :         </ul>


   33 :         {% if form.errors %}


Traceback:
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/srv/www/test.me/localhost/test/views.py" in profile
  102.              'unread_messages': unread_messages})
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/shortcuts/__init__.py" in render
  44.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/loader.py" in render_to_string
  188.         return t.render(context_instance)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in render
  123.             return self._render(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in _render
  117.         return self.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/debug.py" in render_node
  73.             result = node.render(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in render
  880.                     resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in resolve
  653.             value = self._resolve_lookup(context)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/template/base.py" in _resolve_lookup
  692.                             raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute

Exception Type: TemplateSyntaxError at /profile/myuser
Exception Value: Caught VariableDoesNotExist while rendering: Failed lookup for key [avatar] in u'[{}, {'csrf_token': <django.utils.functional.__proxy__ object at 0xb93445ac>}, {'perms': <django.utils.functional.__proxy__ object at 0xb9344cec>, 'messages': <django.contrib.messages.storage.user_messages.LegacyFallbackStorage object at 0xb936258c>, 'user': <django.utils.functional.SimpleLazyObject object at 0xb9344bcc>}, {}, {'LANGUAGES': (('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese')), 'LANGUAGE_BIDI': False, 'LANGUAGE_CODE': 'en-us'}, {'MEDIA_URL': 'http://test.me/media/'}, {'STATIC_URL': '/static/'}, {'messages': <django.contrib.messages.storage.user_messages.LegacyFallbackStorage object at 0xb936258c>}, {'messages': [], 'user': <User: myuser>, 'form': <localhost.test.forms.messagesForm object at 0xb936270c>, 'unread_messages': []}, {'block': <Block Node: content. Contents: [<Text Node: 'n<center>n    '>, <If node>, <Text Node: 'n    n<h2>Describe '>, <Variable Node: user.username>, <Text Node: ' in three messages!</h2>nn<d'>, <django.template.base.SimpleNode object at 0xb937772c>, <Text Node: 'n</div>nn<form id="messages_'>, <Variable Node: user.id>, <Text Node: '" id="id_user" /></li> n '>, <If node>, <Text Node: 'n<input type="submit" val'>, <If node>, <Text Node: 'nn'>]>}]'
  

Это так странно, потому что в другом шаблоне это работает без ошибок.

Можете ли вы мне помочь? Спасибо.

Комментарии:

1. Вы передаете переменную ‘avatar’ из представления в шаблон?

2. @Alex Jillard Какой должна быть переменная ‘avatar’?

Ответ №1:

Из документов django-avatar:

{% render_avatar avatar [size in pixels] %}

Учитывая фактический avatar.models.Avatar экземпляр объекта, отображает HTML img тег для представления этого аватара в запрошенном размере.

Итак, на ваш взгляд, вам нужно получить аватар, связанный с пользователем: avatar = Avatar.objects.get(user=request.user )

Затем передайте эту переменную в шаблон.

Комментарии:

1. как я могу импортировать модель аватара? аватар.модели. Аватар не работает.

2. Я скопировал весь каталог avatar в свой проект и теперь могу импортировать avatar. Проблема в том, что .get не работает, потому что MultipleObjectsReturned: get() returned more than one Avatar -- it returned 3 как я могу исправить?

3. Вы можете использовать . filter() вместо .get(), хотя вам нужно будет выяснить, какой из возвращенных аватаров следует использовать.

4. Исправлено с помощью: avatar = Avatar.objects.filter(user=target_user).order_by('-primary')[0]