Is there any easy way to do so?
I'm sorry, I wasn't clear. I meant set/change the choices attribute after a model has been initialized.
Luiz C.
2010-03-05 18:15:55
+1
A:
You can set the choices attribute to any iterable: http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices
I haven't tested this myself so I'm not sure when the choices attribute is actually evaluated, but you may be able to assign a generator function that would calculate your desired choices.
You might also investigate using the Model post_init signal: http://docs.djangoproject.com/en/1.1/ref/signals/#post-init
This will give you access to your model after Django has initialized it and so you could set the choices at that time. You'd probably want to go through the "_meta" interface like so:
instance._meta.get_field_by_name('FIELD_NAME')[0].choices = [<choices>...]
Brian Luft
2010-03-05 18:22:39
That almost worked. I can see the current choices, but if I try to set it to a different value, I get the error: AttributeError: can't set attribute.
Luiz C.
2010-03-05 18:37:24
Poking around in the fields source, you can see that "choices" is a read-only property:http://code.djangoproject.com/browser/django/tags/releases/1.1.1/django/db/models/fields/__init__.py#L296Try setting to "_choices" instead. This works in the shell but I won't make any guarantees about unintended consequences.
Brian Luft
2010-03-05 19:26:45
Found a big problems using this method. The choices property when changed, changes the model throughout the server, which means that later requests will have the new choices value.
Luiz C.
2010-03-08 14:52:17
Right - this would essentially change the model definition. Backtracking, does it work if you set _choices on the model instance itself? YourModel.yourfield._choices = [...]
Brian Luft
2010-03-08 16:18:41
There are two parts to this problem: form and model level. The form level is very simple to implement and is used when displaying a view/edit page for an entry. The model level is more complex and is used only when displaying a table that lists each entry and some of its properties. That's why this solution doesn't work for this particular case. I took another approach by using a template tag that calls a class method that retrieves the correct display name. Thanks anyways.
Luiz C.
2010-03-08 18:13:31