I am getting the error, [ 'ModelChoiceField' object has no attribute
'to_field_name' ],
when I try to use the following model (from an open source library) in the
ModelChoiceField with python 2.7.3
This is the model in question.
https://sourcegraph.com/github.com/celery/django-
celery/symbols/python/djcelery/models/IntervalSchedule#examples
This is the code that causes the error in a form. (The original code was a
form that inherited from the ModelChoiceField, but ModelChoiceField itself
also gives the error. )
{{{#!python
widgets={'interval': ModelChoiceField(
queryset=IntervalSchedule.objects.all(), empty_label=" :-( ")}
}}}
The modelform, based on PeriodicTask in which the widget is changed, is
called by modelformset_factory.
(from djcelery.models import PeriodicTask, IntervalSchedule )
/usr/local/lib/python2.7/dist-packages/django/forms/models.py in
prepare_value
{{{#!python
def prepare_value(self, value):
if hasattr(value, '_meta'):
if self.to_field_name:
return value.serializable_value(self.to_field_name)
else:
return value.pk
return super(ModelChoiceField, self).prepare_value(value)
}}}
Django Version: 1.6
Exception Type: AttributeError
Exception Value:
'ModelChoiceField' object has no attribute 'to_field_name'
Exception Location: /usr/local/lib/python2.7/dist-
packages/django/forms/models.py in prepare_value, line 1115
Python Executable: /usr/bin/python
Python Version: 2.7.3
I do see the to_field_name in the code on
https://github.com/django/django/blob/stable/1.6.x/django/forms/models.py
but it is initialized on init.
So could this be race condition bug?
(Since I don't get the error with the roughly same code if the widget is
not changed. )
(Am not clicking easy pickings due to the possibility of it being a race
bug. Getting the to_field_name out of the init and into the class would be
easy enough to fix this bug, but if something else is going on... )
--
Ticket URL: <https://code.djangoproject.com/ticket/22000>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* needs_better_patch: => 0
* needs_tests: => 0
* needs_docs: => 0
Comment:
Changing the form directly works, but not using a widget.
interval = ModelChoiceField(
queryset=IntervalSchedule.objects.all(),initial=PeriodicTask.interval,
empty_label="...", required=False)
--
Ticket URL: <https://code.djangoproject.com/ticket/22000#comment:1>
* status: new => closed
* resolution: => invalid
Comment:
A model choice field is not a widget, it is not correct to use it in
`widgets`.
I'm closing this ticket, because it appears to be an issue with your code,
not Django. If you need further help customising the form in your code,
please see wiki:UseSupportChannels
--
Ticket URL: <https://code.djangoproject.com/ticket/22000#comment:2>
Comment (by Alasdair):
Sorry, I got the link wrong in the previous comment. I meant to link to
TicketClosingReasons/UseSupportChannels
--
Ticket URL: <https://code.djangoproject.com/ticket/22000#comment:3>