使用Django Admin上传图像时出现TemplateSyntaxError

时间:2011-04-28 10:43:03

标签: django django-admin django-models

我尝试了"Uploading images using Django Admin?"的例子,但不幸的是我一直都失败了。

模型是:

from django.db import models
from django.contrib import admin

class Celebrity(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name


class Image(models.Model):
    celebrity = models.ForeignKey(Celebrity)
    image = models.ImageField('Bild', upload_to="files/")

    def __unicode__(self):
       return self.image

class InlineImage(admin.TabularInline):
    model = Image

class CelebrityAdmin(admin.ModelAdmin):
    inlines = [InlineImage]

admin.site.register(Celebrity, CelebrityAdmin)

MEDIA_ROOT是:

MEDIA_ROOT =  'c:/python/django/apps/af/neu/images/media/'

这是网址:

url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{ 'document_root': 'c:/python/django/apps/af/neu/images/media/files' }),

# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),

使用此配置上传有效,但当我尝试编辑时,我会收到以下追溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/admin/image/celebrity/3/

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',
 'debug_toolbar',
 'images.image']
Installed Middleware:
('debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Template error:
In template c:\python\lib\site-packages\django\contrib\admin\templates\admin\edit_inline\tabular.html, error at line 27
   Caught TypeError while rendering: coercing to Unicode: need string or buffer, ImageFieldFile found
   17 : 


   18 :      <tbody>


   19 :      {% for inline_admin_form in inline_admin_formset %}


   20 :         {% if inline_admin_form.form.non_field_errors %}


   21 :         <tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr>


   22 :         {% endif %}


   23 :         <tr class="{% cycle "row1" "row2" %} {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last %} empty-form{% endif %}"


   24 :              id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">


   25 :         <td class="original">


   26 :           {% if inline_admin_form.original or inline_admin_form.show_url %}<p>


   27 :           {% if inline_admin_form.original %}  {{ inline_admin_form.original }} {% endif %}


   28 :           {% if inline_admin_form.show_url %}<a href="../../../r/{{ inline_admin_form.original_content_type_id }}/{{ inline_admin_form.original.id }}/">{% trans "View on site" %}</a>{% endif %}


   29 :             </p>{% endif %}


   30 :           {% if inline_admin_form.has_auto_field %}{{ inline_admin_form.pk_field.field }}{% endif %}


   31 :           {{ inline_admin_form.fk_field.field }}


   32 :           {% spaceless %}


   33 :           {% for fieldset in inline_admin_form %}


   34 :             {% for line in fieldset %}


   35 :               {% for field in line %}


   36 :                 {% if field.is_hidden %} {{ field.field }} {% endif %}


   37 :               {% endfor %}


Traceback:
File "C:\Python\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python\lib\site-packages\django\contrib\admin\options.py" in wrapper
  307.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  79.         response = view_func(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\contrib\admin\sites.py" in inner
  197.             return view(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\utils\decorators.py" in _wrapper
  28.             return bound_func(*args, **kwargs)
File "C:\Python\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\utils\decorators.py" in bound_func
  24.                 return func(self, *args2, **kwargs2)
File "C:\Python\lib\site-packages\django\db\transaction.py" in inner
  217.                 res = func(*args, **kwargs)
File "C:\Python\lib\site-packages\django\contrib\admin\options.py" in change_view
  1030.         return self.render_change_form(request, context, change=True, obj=obj)
File "C:\Python\lib\site-packages\django\contrib\admin\options.py" in render_change_form
  708.         ], context, context_instance=context_instance)
File "C:\Python\lib\site-packages\django\shortcuts\__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "C:\Python\lib\site-packages\django\template\loader.py" in render_to_string
  188.         return t.render(context_instance)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  123.             return self._render(context)
File "C:\Python\lib\site-packages\django\test\utils.py" in instrumented_test_render
  57.     return self.nodelist.render(context)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python\lib\site-packages\django\template\loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "C:\Python\lib\site-packages\django\test\utils.py" in instrumented_test_render
  57.     return self.nodelist.render(context)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python\lib\site-packages\django\template\loader_tags.py" in render
  127.         return compiled_parent._render(context)
File "C:\Python\lib\site-packages\django\test\utils.py" in instrumented_test_render
  57.     return self.nodelist.render(context)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python\lib\site-packages\django\template\loader_tags.py" in render
  64.             result = block.nodelist.render(context)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python\lib\site-packages\django\template\defaulttags.py" in render
  227.                 nodelist.append(node.render(context))
File "C:\Python\lib\site-packages\django\template\loader_tags.py" in render
  170.             return self.render_template(template, context)
File "C:\Python\lib\site-packages\django\template\loader_tags.py" in render_template
  141.         output = template.render(context)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  123.             return self._render(context)
File "C:\Python\lib\site-packages\django\test\utils.py" in instrumented_test_render
  57.     return self.nodelist.render(context)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python\lib\site-packages\django\template\defaulttags.py" in render
  227.                 nodelist.append(node.render(context))
File "C:\Python\lib\site-packages\django\template\defaulttags.py" in render
  311.             return self.nodelist_true.render(context)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python\lib\site-packages\django\template\defaulttags.py" in render
  311.             return self.nodelist_true.render(context)
File "C:\Python\lib\site-packages\django\template\base.py" in render
  744.                 bits.append(self.render_node(node, context))
File "C:\Python\lib\site-packages\django\template\debug.py" in render_node
  73.             result = node.render(context)
File "C:\Python\lib\site-packages\django\template\debug.py" in render
  92.             output = force_unicode(output)
File "C:\Python\lib\site-packages\django\utils\encoding.py" in force_unicode
  71.                 s = unicode(s)

Exception Type: TemplateSyntaxError at /admin/image/celebrity/3/
Exception Value: Caught TypeError while rendering: coercing to Unicode: need string or buffer, ImageFieldFile found

我也尝试过MEDIA_ROOT:

MEDIA_ROOT = os.path.join(os.path.dirname(file), "media").replace(r"\\", "//"),

MEDIA_ROOT = os.path.join(os.path.dirname(file), "media").replace("\\", "//"),

但后来甚至没有上传工作

所以我真的很无能为力。任何帮助都非常感谢

2 个答案:

答案 0 :(得分:6)

只需更改Image类

unicode 功能即可
class Image(models.Model):
    celebrity = models.ForeignKey(Celebrity)
    image = models.ImageField('Bild', upload_to="files/")

    def __unicode__(self):
       return self.image.name

您还可以参考this讨论以供参考。我引用了此错误的原因:

  

此问题的问题最终与表单无关   他们自己,但是图像模型的 unicode 方法。   ImageField的较旧实现具有自己的 unicode 方法,所以

def __unicode__(self):
     return self.file
  

工作得很好。现在需要

def __unicode__(self):
    return self.file.name
  

达到同样的效果。

答案 1 :(得分:2)

回溯会告诉您究竟发生了什么。错误发生在__unicode__类的Image方法中 - 您在那里返回image属性,但这不是字符串,因此无法输出为unicode。

请尝试返回image.url