Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 3, Admin Autocomplete: object has no attribute '__unicode__' #471

Closed
raratiru opened this issue Feb 24, 2014 · 3 comments
Closed

Comments

@raratiru
Copy link

Hallo, trying to implement Admin Autocomplete in a Python 3.3 environment and I get the following error:

Request Method:     GET
Request URL:    http://127.0.0.1:8000/admin/auto/tst/foreignkey_autocomplete/?search_fields=location_en%2Clocation_el&app_label=earth&model_name=location&q=achar
Django Version:     1.6.2
Exception Type:     AttributeError
Exception Value:    

'Location' object has no attribute '__unicode__'

Exception Location:     /home/flyer/.virtualenvs/noze/lib/python3.3/site-packages/django_extensions/admin/__init__.py in <lambda>, line 88
Python Executable:  /home/flyer/.virtualenvs/noze/bin/python
Python Version:     3.3.2 

My Model is the following:

class Location (models.Model):
    municipality_key = models.ForeignKey(
        Municipality,
        verbose_name=_('Municipality'),
        )
    location = models.CharField(
        max_length=127,
        verbose_name=_('Location'),
        )

    def __str__(self):
        return '{0}: {1}'.format(self.municipality_key, self.location)

    class Meta(object):
        verbose_name = _('Location')
        verbose_name_plural = _('Locations')

When I replace def __str__(self): with def __unicode__(self): everything works as expected.

@mounirmesselmeni
Copy link
Contributor

You can make your code run into Python2 and Python3 and fixing this error by using the python_2_unicode_compatible decorator in your model.

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Location (models.Model):
    municipality_key = models.ForeignKey(
        Municipality,
        verbose_name=_('Municipality'),
        )
    location = models.CharField(
        max_length=127,
        verbose_name=_('Location'),
        )

    def __str__(self):
        return '{0}: {1}'.format(self.municipality_key, self.location)

    class Meta(object):
        verbose_name = _('Location')
        verbose_name_plural = _('Locations')

@trbs
Copy link
Member

trbs commented Nov 4, 2014

Thanks @mounirmesselmeni !
@raratiru I hope this answers your question.

commited b32ffe9 as well.

@trbs trbs closed this as completed Nov 4, 2014
@raratiru
Copy link
Author

raratiru commented Nov 4, 2014

Thank you, this is great news!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants