Opened 16 years ago

Closed 15 years ago

Last modified 12 years ago

#8774 closed (invalid)

ImageField errors in admin inline editing

Reported by: ramin Owned by: nobody
Component: contrib.admin Version: dev
Severity: Keywords: imagefield admin inline
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Jacob)

When trying to edit a model that has another model inlined in the admin the following error occurs. This doesn't occur when creating a new instance. The error was first sighted from an SVN version on Friday 28.8.2008 and is still present in rev 8814.

[original html traceback removed -JKM]

Attachments (1)

ticket8774.zip (4.2 KB ) - added by vung 16 years ago.
the project I used for testing

Download all attachments as: .zip

Change History (20)

comment:1 by Jacob, 16 years ago

Description: modified (diff)

Cleared out impossible-to-read traceback.

ramin, there's a "switch to copy-paste view" button in the error page; please us it and post the readable message!

comment:2 by Jacob, 16 years ago

BTW, I have a inlines with ImageFields working fine here, so this is likely a configuration error.

comment:3 by Jacob, 16 years ago

Resolution: worksforme
Status: newclosed

Without a readable traceback we can't do anything about this. ramin, feel free to reopen if you can provide one.

comment:4 by ramin, 16 years ago

Resolution: worksforme
Status: closedreopened

Here's a readable traceback. Sorry about the earlier problems...

Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/blogengine/entry/7792/
Django Version: 1.0-beta_2-SVN-8814
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',

'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.sites',
'tagging',
'sorl.thumbnail',
'lifeofjalo.blogengine']

Installed Middleware:
('django.middleware.common.CommonMiddleware',

'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware')

Template error:
In template /usr/lib/python2.5/site-packages/django/contrib/admin/templates/admin/edit_inline/tabular.html, error at line 24

Caught an exception while rendering: coercing to Unicode: need string or buffer, ImageFieldFile found
14 : {% endfor %}

15 : {% if inline_admin_formset.formset.can_delete %}<th>{% trans "Delete?" %}</th>{% endif %}

16 : </tr></thead>

17 :

18 : {% for inline_admin_form in inline_admin_formset %}

19 :

20 : <tr class="{% cycle row1,row2 %} {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}">

21 :

22 : <td class="original">

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

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

25 : {% 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 %}

26 : </p>{% endif %}

27 : {{ inline_admin_form.pk_field.field }}

28 : {% spaceless %}

29 : {% for fieldset in inline_admin_form %}

30 : {% for line in fieldset %}

31 : {% for field in line %}

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

33 : {% endfor %}

34 : {% endfor %}

Traceback:
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py" in get_response

  1. response = callback(request, *callback_args, callback_kwargs)

File "/usr/lib/python2.5/site-packages/django/contrib/admin/sites.py" in root

  1. return self.model_page(request, *url.split('/', 2))

File "/usr/lib/python2.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func

  1. response = view_func(request, *args, kwargs)

File "/usr/lib/python2.5/site-packages/django/contrib/admin/sites.py" in model_page

  1. return admin_obj(request, rest_of_url)

File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in call

  1. return self.change_view(request, unquote(url))

File "/usr/lib/python2.5/site-packages/django/db/transaction.py" in _commit_on_success

  1. res = func(*args, kw)

File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in change_view

  1. return self.render_change_form(request, context, change=True, obj=obj)

File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in render_change_form

  1. ], context, context_instance=template.RequestContext(request))

File "/usr/lib/python2.5/site-packages/django/shortcuts/init.py" in render_to_response

  1. return HttpResponse(loader.render_to_string(*args, kwargs), httpresponse_kwargs)

File "/usr/lib/python2.5/site-packages/django/template/loader.py" in render_to_string

  1. return t.render(context_instance)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. return self.nodelist.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. bits.append(self.render_node(node, context))

File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node

  1. result = node.render(context)

File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render

  1. return compiled_parent.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. return self.nodelist.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. bits.append(self.render_node(node, context))

File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node

  1. result = node.render(context)

File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render

  1. return compiled_parent.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. return self.nodelist.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. bits.append(self.render_node(node, context))

File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node

  1. result = node.render(context)

File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render

  1. result = self.nodelist.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. bits.append(self.render_node(node, context))

File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node

  1. result = node.render(context)

File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render

  1. nodelist.append(node.render(context))

File "/usr/lib/python2.5/site-packages/django/template/loader_tags.py" in render

  1. return t.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. return self.nodelist.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. bits.append(self.render_node(node, context))

File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node

  1. result = node.render(context)

File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render

  1. nodelist.append(node.render(context))

File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render

  1. return self.nodelist_true.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. bits.append(self.render_node(node, context))

File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node

  1. result = node.render(context)

File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py" in render

  1. return self.nodelist_true.render(context)

File "/usr/lib/python2.5/site-packages/django/template/init.py" in render

  1. bits.append(self.render_node(node, context))

File "/usr/lib/python2.5/site-packages/django/template/debug.py" in render_node

  1. raise wrapped

Exception Type: TemplateSyntaxError at /admin/blogengine/entry/7792/
Exception Value: Caught an exception while rendering: coercing to Unicode: need string or buffer, ImageFieldFile found

Original Traceback (most recent call last):

File "/usr/lib/python2.5/site-packages/django/template/debug.py", line 71, in render_node

result = node.render(context)

File "/usr/lib/python2.5/site-packages/django/template/debug.py", line 87, in render

output = force_unicode(self.filter_expression.resolve(context))

File "/usr/lib/python2.5/site-packages/django/utils/encoding.py", line 49, in force_unicode

s = unicode(s)

TypeError: coercing to Unicode: need string or buffer, ImageFieldFile found

comment:5 by Jacob, 16 years ago

Please also post your model declaration and admin declaration. Again, plenty of people are using inline image fields, so you need to show us as much information as possible so that we can figure out what's different in your set up.

Also, please put your code in code blocks by surrounding the snippets with {{{ and }}} or by using the "code snippet" button above the comment form. Read the WikiFormatting page if you need more help with that.

comment:6 by ramin, 16 years ago

The following models are used:

class Entry(models.Model):
    pub_date = models.DateTimeField('date published')
    created = models.DateTimeField(auto_now_add=True, editable=False)
    edited = models.DateTimeField(auto_now=True, editable=False)
    title = models.CharField(max_length=200, blank=True)
    title_fi = models.CharField(max_length=200, blank=True)
    is_memorial = models.BooleanField('Use special layout?', default=False)

class Image(models.Model):
    entry = models.ForeignKey(Entry, related_name='images')
    file = models.ImageField(upload_to="%Y")
    caption = models.TextField()
    caption_fi = models.TextField()

And forms:

class ImageForm(forms.ModelForm):
    file = forms.ImageField()
    caption = forms.CharField(label='Default caption', widget=forms.Textarea)
    caption_fi = forms.CharField(label='Caption in Finnish', required=False, widget=forms.Textarea)

class ImageInline(admin.TabularInline):
    model = Image
    extra = 1
    form = ImageForm

class EntryForm(forms.ModelForm):
    pub_date = forms.DateField(label='Publication date', initial=datetime.date.today() + datetime.timedelta(1))
    title = forms.CharField(max_length=200, required=False)
    title_fi = forms.CharField(label='Finnish title', max_length=200, required=False)
    is_memorial = forms.BooleanField(label='Use special layout?', initial=False, required=False)
    tags = forms.CharField(max_length=200,required=False)

class EntryAdmin(admin.ModelAdmin):
    date_hierachy = 'pub_date'
    list_display = ('pub_date', 'title')
    list_filter = ('pub_date',)
    ordering = ('-pub_date',)
    search_fields = ('pub_date', 'title')
    inlines = [
        ImageInline,
    ]
    form = EntryForm

The same error also occurs without a custom admin form for the Image model. In fact I created the custom form when I first encountered the error. I also tried creating a formset to see if it would have solved the issue.

comment:7 by vung, 16 years ago

Works for me, using the above models and forms (I only added the relevant imports). I'm attaching the full project I used; note that it doesn't have the extra applications (tagging and sorl.thumbnail)

Tested with django rev [8803] (what I had), [8814] (the reported one) and [8849] (the current one) with python 2.4.4 and 2.5.2 with sqlite3, psycopg2, and mysql, using files with non-ascii names.
After each test I wiped all *.pyc files. So, at least here, it works in the eighteen combinations that result from the above.

I used a standard debian etch, with its default packages for python (2.4.3), mysql (5.0.32) and posgresql (8.1.11). All python 2.5 related packages were compiled from source - python itself, PIL and db drivers for mysql and psql.

I did not tested with the default admin forms (well, I did, but not in a structured manner and I don't remember which versions).

by vung, 16 years ago

Attachment: ticket8774.zip added

the project I used for testing

comment:8 by Malcolm Tredinnick, 16 years ago

I'm not 100% sure what the original problem is here, but there's certainly a bug. Reading the traceback, the code is blowing up whilst trying to display the debug page. force_unicode() should never fail on a Django model or field. The line where the traceback ends suggests that it's found a __unicode__ attribute on the object, but that method isn't returning a valid unicode string. So there's something funky going on inside file fields or image fields or something. We should never, ever be raising an exception there. The fact that we are says that there's a bug in the implementation, even if just for printing out the debugging page.

comment:9 by vung, 16 years ago

If you add to the Image model the following:

    def __unicode__(self):
        return self.file

then you get what seems to be the above traceback.

force_unicode assumes that if an object has an __unicode__ attribute then passing the object to unicode() will either return an unicode object or raise UnicodeDecodeError.

This of course will fail if someone defines an __unicode __ method that doesn't return an unicode object, or raises some other exception.

comment:10 by Malcolm Tredinnick, 16 years ago

A __unicode__ method that doesn't do return a unicode object is broken. It's incorrect code. Django cannot and should not work around that. The bug to work out is why do we have such a method somewhere inside Django itself (which is what the above traceback looks like).

comment:11 by Jacob, 16 years ago

I don't think we do -- I think this is in the user's code or in the third-party sorl.thumbnail.

ramin: do you have a __unicode__ method on your Image class? If so, what does it look like?

comment:12 by vung, 16 years ago

What I can say for sure is this:

Adding a broken __unicode__ method to the Image model above, I get a traceback identical with the traceback from this ticket.

My traceback can be seen here: http://dpaste.com/75372/

The method isn't present in what was posted here, but the coincidence is big and with the broken method the admin behaves as in the very short description of this ticket:

  • Adding an entry works (as there are no Images that need to be represented)
  • Editind an Entry which has inline Images attached causes the exception, because force_unicode invokes the broken __unicode__ method

Also, the above __unicode__ method would not be broken in revisions before [8244] (file storage refactoring), as before that self.file would be an unicode object and not an ImageFieldFile instance.

comment:13 by Jacob, 16 years ago

Resolution: worksforme
Status: reopenedclosed

I'm convinced that this is a faulty __unicode__ method on one of the involved models. That's the only way I can reproduce it.

comment:14 by ramin, 16 years ago

I did have the above unicode method so that must be at fault. Fixing it fixes the issue.

comment:15 by Adam Nelson, 15 years ago

Component: Template systemdjango.contrib.admin
Resolution: worksforme
Status: closedreopened

I'm seeing this issue in Django 1.0.2 when trying to add a first record to the Score model through the standard admin interface. field.field in the template is trying to render the ImageField because of a foreign key relationship I think. Here are the relevant models:

from django.db import models
from page.models import Page
from phrase.models import Phrase



class ScoreType(models.Model):
    """
    Types of score weights
    """
    #affiliate
    name = models.CharField(max_length=50,unique=True)
    description = models.CharField(max_length=255)
    weight = models.FloatField() 

    def __unicode__(self):
        return self.name
    
    
class Score(models.Model):
    """
    Score page
    """
    score = models.FloatField() 
    #flag tinyint(1) unsigned DEFAULT NULL
    #status varchar(30)  DEFAULT 'pending'
    #review varchar(30)  DEFAULT 'not reviewed'
    date = models.DateTimeField(auto_now_add=True)
    type = models.ForeignKey(ScoreType)
    page = models.ForeignKey(Page)

    class Meta:
        unique_together = ('page','type')

    def __unicode__(self):
        return self.score

class ScoreDetail(models.Model):
    """
    Detail page processed by Transparency
    """
    #line_number int(11) DEFAULT NULL
    #line_source text
    date = models.DateTimeField(auto_now_add=True)
    phrase = models.ForeignKey(Phrase)
    score = models.ForeignKey(Score)

    def __unicode__(self):
        return u'%s on %s' % (self.phrase, self.date)

from django.db import models
from company.models import Company
from campaign.models import Campaign
from log.models import Batch,Message

# For handling html content as a file
from django.core.files.storage import default_storage as s3_storage
from django.core.files.base import ContentFile
from django.core.cache import cache


# Create your models here.
class Page(models.Model):
    """
    Page process by Transparency
    """
    sub_id_1 = models.CharField(max_length=255,blank=True)
    sub_id_2 = models.CharField(max_length=255,blank=True)
    sub_id_3 = models.CharField(max_length=255,blank=True)
    sub_id_4 = models.CharField(max_length=255,blank=True)
    image = models.ImageField(upload_to='performline_page_image',blank=True)
    image_url = models.URLField(verify_exists=False)
    content = models.FileField(upload_to='performline_page_source',blank=True)
    content_local = models.TextField(blank=True)
    date = models.DateTimeField(auto_now_add=True)
    affiliate = models.ForeignKey(Company)
    campaign = models.ForeignKey(Campaign)

    def __unicode__(self):
        return self.image

class PageDisplay(Page):
    """
    Detail of page of type display
    """
    url = models.URLField(verify_exists=False,blank=True) 
    referrer = models.URLField(verify_exists=False,blank=True) 
    browser = models.CharField(max_length=255,blank=True)

    def __unicode__(self):
        return self.url
    
class PageEmail(Page):
    """
    Detail of page of type email processed by Transparency
    """
    token = models.PositiveIntegerField()
    header = models.TextField()
    source = models.CharField(max_length=10)
    hash = models.CharField(max_length=255)
    batch = models.ForeignKey(Batch)
    message = models.ForeignKey(Message)

    def __unicode__(self):
        return self.source

from django.db import models
from campaign.models import Campaign


# Create your models here.
LOGIC_CHOICES = (
                 ('banned','banned'),
                 ('expected','expected'),
                 )

class Phrase(models.Model):
    """
    Returns phrase for Transparency
    """
    phrase = models.CharField(max_length=255)
    logic = models.CharField(max_length=30,choices=LOGIC_CHOICES)
    display = models.BooleanField()
    search = models.BooleanField()
    email = models.BooleanField()
    landing = models.BooleanField()
    campaign = models.ForeignKey(Campaign)
    # category = models.ForeignKey(Category)
    
    class Meta:
        unique_together = ('phrase','logic','display','search','email','landing','campaign')

    def __unicode__(self):
        return u'%s is %s' % (self.phrase, self.logic)

class PhraseCategory(models.Model):
    """
    Returns phrase category
    """
    name = models.CharField(max_length=50) 
    description = models.CharField(max_length=255)
    logic = models.CharField(max_length=30,choices=LOGIC_CHOICES)

    class Meta:
        verbose_name_plural = 'phrase categories'
    def __unicode__(self):
        return self.name
Environment:

Request Method: GET
Request URL: http://staging.performline.com/admin/score/score/add/
Django Version: 1.0.2 final SVN-5
Python Version: 2.5.4
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.humanize',
 'notification',
 'django_openid',
 'emailconfirmation',
 'django_extensions',
 'robots',
 'mailer',
 'announcements',
 'oembed',
 'djangodblog',
 'pagination',
 'timezones',
 'ajax_validation',
 'uni_form',
 'basic_profiles',
 'staticfiles',
 'account',
 'misc',
 'about',
 'campaign',
 'click',
 'company',
 'log',
 'page',
 'phrase',
 'score',
 'violation',
 'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django_openid.consumer.SessionConsumer',
 'account.middleware.LocaleMiddleware',
 'django.middleware.doc.XViewMiddleware',
 'pagination.middleware.PaginationMiddleware',
 'djangodblog.middleware.DBLogMiddleware')


Template error:
In template /Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 12
   Caught an exception while rendering: coercing to Unicode: need string or buffer, ImageFieldFile found
   2 :   {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}


   3 :   {% if fieldset.description %}<div class="description">{{ fieldset.description|safe }}</div>{% endif %}


   4 :   {% for line in fieldset %}


   5 :       <div class="form-row{% if line.errors %} errors{% endif %} {% for field in line %}{{ field.field.name }} {% endfor %} ">


   6 :       {{ line.errors }}


   7 :       {% for field in line %}


   8 :       <div{% if not line.fields|length_is:"1" %} class="field-box"{% endif %}>


   9 :           {% if field.is_checkbox %}


   10 :               {{ field.field }}{{ field.label_tag }}


   11 :           {% else %}


   12 :               {{ field.label_tag }} {{ field.field }} 


   13 :           {% endif %}


   14 :           {% if field.field.field.help_text %}<p class="help">{{ field.field.field.help_text|safe }}</p>{% endif %}


   15 :       </div>


   16 :       {% endfor %}


   17 :       </div>


   18 :   {% endfor %}


   19 : </fieldset>


   20 : 

Traceback:
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/core/handlers/base.py" in get_response
  86.                 response = callback(request, *callback_args, **callback_kwargs)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/contrib/admin/sites.py" in root
  157.                 return self.model_page(request, *url.split('/', 2))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/contrib/admin/sites.py" in model_page
  176.         return admin_obj(request, rest_of_url)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/contrib/admin/options.py" in __call__
  191.             return self.add_view(request)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/db/transaction.py" in _commit_on_success
  238.                 res = func(*args, **kw)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/contrib/admin/options.py" in add_view
  539.         return self.render_change_form(request, context, add=True)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/contrib/admin/options.py" in render_change_form
  408.         ], context, context_instance=template.RequestContext(request))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/shortcuts/__init__.py" in render_to_response
  18.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/loader.py" in render_to_string
  107.     return t.render(context_instance)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  176.         return self.nodelist.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  768.                 bits.append(self.render_node(node, context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/debug.py" in render_node
  71.             result = node.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/loader_tags.py" in render
  97.         return compiled_parent.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  176.         return self.nodelist.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  768.                 bits.append(self.render_node(node, context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/debug.py" in render_node
  71.             result = node.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/loader_tags.py" in render
  97.         return compiled_parent.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  176.         return self.nodelist.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  768.                 bits.append(self.render_node(node, context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/debug.py" in render_node
  71.             result = node.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/loader_tags.py" in render
  24.         result = self.nodelist.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  768.                 bits.append(self.render_node(node, context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/debug.py" in render_node
  71.             result = node.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/defaulttags.py" in render
  148.                 nodelist.append(node.render(context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/loader_tags.py" in render
  111.             return self.template.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  176.         return self.nodelist.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  768.                 bits.append(self.render_node(node, context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/debug.py" in render_node
  71.             result = node.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/defaulttags.py" in render
  148.                 nodelist.append(node.render(context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/defaulttags.py" in render
  148.                 nodelist.append(node.render(context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/defaulttags.py" in render
  246.             return self.nodelist_false.render(context)
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/__init__.py" in render
  768.                 bits.append(self.render_node(node, context))
File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/debug.py" in render_node
  81.             raise wrapped

Exception Type: TemplateSyntaxError at /admin/score/score/add/
Exception Value: Caught an exception while rendering: coercing to Unicode: need string or buffer, ImageFieldFile found

Original Traceback (most recent call last):
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/debug.py", line 71, in render_node
    result = node.render(context)
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/template/debug.py", line 87, in render
    output = force_unicode(self.filter_expression.resolve(context))
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/utils/encoding.py", line 49, in force_unicode
    s = unicode(s)
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/forms/forms.py", line 333, in __unicode__
    return self.as_widget()
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/forms/forms.py", line 365, in as_widget
    return widget.render(name, data, attrs=attrs)
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/contrib/admin/widgets.py", line 224, in render
    output = [self.widget.render(name, value, *args, **kwargs)]
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/forms/widgets.py", line 360, in render
    options = self.render_options(choices, [value])
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/forms/widgets.py", line 376, in render_options
    for option_value, option_label in chain(self.choices, choices):
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/forms/models.py", line 623, in __iter__
    yield self.choice(obj)
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/forms/models.py", line 636, in choice
    return (key, self.field.label_from_instance(obj))
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/forms/models.py", line 679, in label_from_instance
    return smart_unicode(obj)
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/utils/encoding.py", line 35, in smart_unicode
    return force_unicode(s, encoding, strings_only, errors)
  File "/Users/adam/Documents/workspace/performline-albatross/src/pinax/lib/python2.5/site-packages/django/utils/encoding.py", line 49, in force_unicode
    s = unicode(s)
TypeError: coercing to Unicode: need string or buffer, ImageFieldFile found

comment:16 by Adam Nelson, 15 years ago

When removing page.Page.image field from the models, this works fine. It looks that the Django admin doesn't like a ForeignKey going to a model with an ImageField?

Two caveats here are that there were no ImageField entries populated in the Page model and I'm using django-storages (specifically s3boto.py) as a file storage backend.

comment:17 by Adam Nelson, 15 years ago

Here is the problem. In the Page model, the unicode function returns an image object:

def unicode(self):

return self.image

Either the admin templates should handle non-unicode objects or there should be a note at http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.__unicode about not using FileField objects that may be referenced as part of a ForeignKey?

comment:18 by Karen Tracey, 15 years ago

Resolution: invalid
Status: reopenedclosed

The admin should not (and in fact, cannot) handle non-unicode objects returned by a model's __unicode__ method. A __unicode__ method should return a unicode object. If it does not, Python will attempt to coerce the returned value to unicode. If Python cannot do this conversion, it generates the exception, which is pretty clear:

coercing to Unicode: need string or buffer, ImageFieldFile found

Here, instead of returning unicode, a __unicode__ method returned an ImageFieldFile, and Python cannot coerce that to unicode. The only possible fix is to make the __unicode__ method return unicode or something coercable to unicode.

There is nothing Django-specific about the requirements for __unicode__. This is a Python-defined function:

http://docs.python.org/reference/datamodel.html?highlight=__unicode__#object.__unicode

Django's doc discusses element of __unicode__ implementation specific to Django, I don't believe it ought to reiterate the basic Python requirements for the function. It certainly should not attempt to list all the things that a __unicode__ function should not return, as that list would be infinitely large.

comment:19 by Jacob, 12 years ago

milestone: 1.0

Milestone 1.0 deleted

Note: See TracTickets for help on using tickets.
Back to Top