I'm trying to update my model, so when a BooleanField is checked via the admin, it updates all the other rows to be reset to False (0). But when I keep doing this it just returns the following TypeError: 'bool' object is not iterable
Here is my model:
class Contact(models.Model):
name = models.CharField(max_length=255)
telephone = models.CharField(max_length=255,blank=True)
email = models.CharField(max_length=255,blank=True)
primary_contact = models.BooleanField('Primary Contact')
def __unicode__(self):
return self.name
def make_primary(self):
Contact.objects.filter(id!=self.id).update(primary_contact=False)
def save(self, *args, **kwargs):
if (self.primary_contact == True):
self.make_primary()
super(Contact, self).save(*args, **kwargs)
I'm Trying to update my rows during save() using a custom method called make_primary(). It feels like there is something super simple and obvious that I need to do. I'm new to Django, so it's a bit of a learning curve.
Any help and advice would be greatly appreciated.
Thanks :)
EDIT:
As requested here is my traceback / error below. Also, I updated my code to use exclude instead and the error has changed to: 'long' object is not iterable
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/contact/contact/1/
Django Version: 1.8.2
Python Version: 2.7.6
Installed Applications:
('grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce',
'adminsortable',
'taggit',
'contact')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in wrapper
616. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/sites.py" in inner
233. return view(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/adminsortable/admin.py" in change_view
231. form_url='', extra_context=extra_context)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in change_view
1519. return self.changeform_view(request, object_id, form_url, extra_context)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapper
34. return bound_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in bound_func
30. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/Library/Python/2.7/site-packages/django/utils/decorators.py" in inner
145. return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1467. self.save_model(request, new_object, form, not add)
File "/Library/Python/2.7/site-packages/django/contrib/admin/options.py" in save_model
1078. obj.save()
File "/Users/[hidden]/Sites/[hidden]/contact/models.py" in save
37. self.make_primary()
File "/Users/[hidden]/Sites/[hidden]/contact/models.py" in make_primary
28. for oc in other_contacts:
Exception Type: TypeError at /admin/contact/contact/1/
Exception Value: 'long' object is not iterable
This line is invalid:
MyModel.objects.filter(id!=self.id)
When you do id!=self.id, the expression evaluates to False, so it's the same as doing filter(False). That's the bool object that is 'not iterable' in your traceback message, it doesn't actually have anything to do with your BooleanField.
When you do filter(id=self.id), you are passing a keyword argument to the filter method. Django doesn't have a way to do not equal as a keyword argument in a filter. You can use exclude() instead.
MyModel.objects.exclude(id=self.id)
Related
I'm working on a legacy django 1.4 project, porting it to django 1.7.
When accessing the django admin interface, in order to show user data I get the aforementioned error.
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/auth/user/1/
Django Version: 1.7.4
Python Version: 2.7.8
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.humanize',
'simple_autocomplete',
'paypal.standard.ipn',
'sorl.thumbnail',
'haystack',
'crispy_forms',
'siteprefs',
'sitegate',
'debug_toolbar',
'modeltranslation',
'rosetta',
# omitted: some project-specific apps
)
Installed Middleware:
('debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "MYENV/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "MYENV/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
583. return self.admin_site.admin_view(view)(*args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
206. return view(request, *args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
1456. return self.changeform_view(request, object_id, form_url, extra_context)
File "MYENV/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "MYENV/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1419. form = ModelForm(instance=obj)
File "MYENV/lib/python2.7/site-packages/django/contrib/auth/forms.py" in __init__
145. super(UserChangeForm, self).__init__(*args, **kwargs)
File "MYENV/lib/python2.7/site-packages/django/forms/models.py" in __init__
333. limit_choices_to = formfield.get_limit_choices_to()
File "MYENV/lib/python2.7/site-packages/django/forms/models.py" in get_limit_choices_to
1126. if callable(self.limit_choices_to):
Exception Type: AttributeError at /admin/auth/user/1/
Exception Value: 'ModelMultipleChoiceField' object has no attribute 'limit_choices_to'
The self object in the offending line is a django.forms.models.ModelMultipleChoiceField instance (of course), the formfield in line 333 (see traceback) is instantiated as formfield = self.fields['groups'].
The error raises even on an empty db (with just one user). I've checked twice but there are no changes in the AUTH_MODEL, in the signals or any OneToOne link to the User model.
I've checked also the external apps for similar issues without any luck. Does anybody had the same issue in the past and can give me an hint on where to search for the source of this error? I'm still reluctant to report a bug to django since I cannot replicate it if I'm unable to define where the error is triggered.
EDIT:
I've verified that the problem arises in every model that has a foreign key (or a M2M, or a O2O). #Alasdair comment was a good suggestion but for sure I do not alter the queryset in all the models so the reason should be elsewhere.
I suggest you try disabling simple_autocomplete. There appears to be a similar issue with django-ajax-selects.
I have been trying to make the basic django-polymorphic example to work.
models.py
from polymorphic import PolymorphicModel, ShowFieldContent
class Project(ShowFieldContent, PolymorphicModel):
topic = models.CharField(max_length=30)
class ArtProject(Project):
artist = models.CharField(max_length=30)
class ResearchProject(Project):
supervisor = models.CharField(max_length=30)
admin.py
from django.contrib import admin
from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin, PolymorphicChildModelFilter
from rapidhealth.core.models import Project, ArtProject, ResearchProject
class ProjectChildAdmin(PolymorphicChildModelAdmin):
base_model = Project
class ProjectAdmin(PolymorphicParentModelAdmin):
base_model = Project
list_filter = (PolymorphicChildModelFilter,)
child_models = (
(Project, ProjectChildAdmin),
(ArtProject, ProjectChildAdmin),
(ResearchProject, ProjectChildAdmin),
)
admin.site.register(Project, ProjectAdmin)
Now when trying to create a new "project" in the admin site I get:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admincore/project/add/?ct_id=42
Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'sekizai',
'mptt',
'south',
'reversion',
'rest_framework',
'polymorphic',
'rapidhealth.core',
'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
372. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
202. return view(request, *args, **kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/polymorphic/admin.py" in add_view
225. return real_admin.add_view(request, form_url, extra_context)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
223. return func(*args, **kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
984. ModelForm = self.get_form(request)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/polymorphic/admin.py" in get_form
484. return super(PolymorphicChildModelAdmin, self).get_form(request, obj, **kwargs)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in get_form
465. return modelform_factory(self.model, **defaults)
File "/home/lucas-fievet/.virtualenvs/rh/local/lib/python2.7/site-packages/django/forms/models.py" in modelform_factory
424. return type(form)(class_name, (form,), form_class_attrs)
Exception Type: TypeError at /admincore/project/add/
Exception Value: cannot create 'NoneType' instances
Does anyone understand what the problem is?
I have tried all kind of changes. When using the default django admin I can create a project.
Thank you,
Lucas
It turned out that specifying explicitly the form to use solved the problem:
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
class ProjectChildAdmin(PolymorphicChildModelAdmin):
base_model = Project
base_form = ProjectForm
For some reason the form is not automatically generated.
I'm getting an error when trying to save to the following model using the admin interface:
models.py
class Answer(models.Model):
a = models.TextField(primary_key=True)
gloss = models.TextField(blank=True)
clean = models.TextField(blank=True)
count = models.IntegerField(blank=True)
p = models.IntegerField(blank=True)
def __unicode__(self):
return u"%s" % self.a
class Meta:
db_table = u'answers'
here's the error message that shows up on the admin interface:
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/emotions/answer/add/
Django Version: 1.4 pre-alpha SVN-16322
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'emo20qBrowser.emotions']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/abe/bin/django-trunk/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/options.py" in wrapper
316. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/views/decorators/cache.py" in _wrapped_view_func
77. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/home/abe/bin/django-trunk/django/db/transaction.py" in inner
211. return func(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/options.py" in add_view
871. if form.is_valid():
File "/home/abe/bin/django-trunk/django/forms/forms.py" in is_valid
121. return self.is_bound and not bool(self.errors)
File "/home/abe/bin/django-trunk/django/forms/forms.py" in _get_errors
112. self.full_clean()
File "/home/abe/bin/django-trunk/django/forms/forms.py" in full_clean
269. self._post_clean()
File "/home/abe/bin/django-trunk/django/forms/models.py" in _post_clean
331. self.instance.clean()
Exception Type: TypeError at /admin/emotions/answer/add/
Exception Value: 'unicode' object is not callable
Okay, I think I figured it out... I'm using a variable/column called "clean". Django's admin interface has a method called "clean()" also, which does some kind of validation. It appears that there was some kind of naming conflict so I changed the variable to name to "cleaned" and then to make sure that it knows what database field to use (I'm using a legacy/preexisting db), I added a db_column option:
cleaned = models.TextField(blank=True,db_column="clean")
It would have been nice to know that "clean" was a reserved identifier in django but at least I only wasted half a day on this django stuff which ostensibly makes database operations easier. To be fair, I just started django this morning and if I would have found and answer on stackoverflow it would have been a breeze to fix.
If anyone knows a better way to handle this, let me know...
I currently have a ModelForm set up in Django, but would like to make one of the fields of the form unrequired. Here's my forms.py:
from django.forms import ModelForm
from add_flair.models import User
class UserForm(ModelForm):
class Meta:
model = User
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['year'].required = False
So I figured out how to override the 'required' attribute of my 'year' field, but when I go to submit a form with no year, I get:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:9999/flair/add/
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',
'project.add_flair']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
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 "/home/coreyf/dev/reddit-calpoly-addflair/project/../project/add_flair/views.py" in add
14. save_user(form, confirm_num)
File "/home/coreyf/dev/reddit-calpoly-addflair/project/../project/add_flair/views.py" in save_user
42. user.save()
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/base.py" in save
460. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/base.py" in save_base
543. for f in meta.local_fields if not isinstance(f, AutoField)]
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/subclassing.py" in inner
28. return func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/subclassing.py" in inner
28. return func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/__init__.py" in get_db_prep_save
276. return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/subclassing.py" in inner
53. return func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/subclassing.py" in inner
53. return func(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/__init__.py" in get_db_prep_value
271. value = self.get_prep_value(value)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/db/models/fields/__init__.py" in get_prep_value
876. return int(value)
Exception Type: ValueError at /flair/add/
Exception Value: invalid literal for int() with base 10: ''
I'm assuming that int() is trying to parse an empty value and throwing an error. Is there any way to fix this? Is there a better way of making a field from a ModelForm unrequired?
Add blank=True, null=True to your field declaration im models.py (and don't forget to reflect this change in DB, by migration or manually).
I'm having a FieldError.
I have a model:
class Foo(models.Model):
__bar = models.TextField(default=lambda: cPickle.dumps(set()), primary_key=True)
def get_bar(self):
return cPickle.loads(str(self.__bar))
def set_bar(self, values):
self.__bar = cPickle.dumps(values)
bar = property(get_bar, set_bar)
I have registered it with the admin in admin.py:
admin.site.register(Foo)
When I runserver and go to /admin, I see Foo in the list. If I click "Add", it works fine, showing the form to add a new Foo. However, if I click "save and add another" or "change" or "Foos", I get a FieldError
FieldError at /admin/appname/Foo/
Cannot resolve keyword '_Foo' into field. Choices are: _Foo__bar, appname
The traceback is:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/appname/foo/
Django Version: 1.2.4
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'pagination',
'apps.appname']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'pagination.middleware.PaginationMiddleware')
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in wrapper
265. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
78. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
190. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapper
21. return decorator(bound_func)(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in bound_func
17. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/options.py" in changelist_view
1097. 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in __len__
80. self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in iterator
271. for row in compiler.results_iter():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in results_iter
677. for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
722. sql, params = self.as_sql()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in as_sql
57. ordering, ordering_group_by = self.get_ordering()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in get_ordering
346. self.query.model._meta, default_order=asc):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in find_ordering_name
375. opts, alias, False)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in setup_joins
1215. "Choices are: %s" % (name, ", ".join(names)))
Exception Type: FieldError at /admin/appname/foo/
Exception Value: Cannot resolve keyword '_Foo' into field. Choices are: _Foo__bar, appname
What could be going on here? I did some searching, and I found similar errors but they seem to have something to do with many-to-many fields, of which I have none. There are other models that reference this one as a foreign key, but that seems unlikely to cause the problem.
Because you've prefixed __bar with two underscores, Python is performing name mangling (doc link) in an attempt to enforce private access to the variable.
Private variables, of course, don't exist in Python, but by using the double-underscore convention you've asked Python to reformat __bar as _(classname)__bar, which is why Django is telling you that "Choices are: _Foo__bar...".
If you wish to signal that bar shouldn't be used outside out the class, I'd recommend the single-underscore notation (also discussed at the link above), which should solve the field issue you're experiencing as single-underscore prefixes are not name mangled.