1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | from django import newforms as forms
from django.db import models
################ models ####################
class BillCode(models.Model):
description = models.CharField(maxlength=20)
class Payment(models.Model):
billCode = models.ForeignKey(BillCode)
################# views ####################
class Choices:
def _choices(self):
return [(e.id, e.description) for e in BillCode.objects.all()]
choices = property(_choices)
class PaymentForm(forms.Form):
billCode_id = forms.ChoiceField(label="Bill Code",
choices=[('','')]+Choices().choices)
|
More like this
- RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 1 year, 7 months ago
- Querying on existence of a relationship by ubernostrum 4 years, 9 months ago
- Hyperlink read-only ForeignKey objects in admin to their change pages by strangefeatures 3 months, 3 weeks ago
- Making prepopulate_from work with ForeignKeys and other sorts of choice fields by josho 3 years, 8 months ago
- Changelist filter by ForeignKey by overclocked 1 year, 6 months ago
Comments
Choices seems to be calculated at the time the module is loaded, and not dynamically (that seems to be what snippet #26 is for). So if you add a new billcode to the database, the select is not updated until the server is restarted.
#
No, that's not correct. To illustrate the way Python properties work:
#
While I haven't tried with newforms, this approach certainly doesn't work with oldforms...
I spent some time trying to setup a field that listed its 5 most common choices at the top, but it would not update to reflect new records until a forced server reload. I can't remember exactly where the problem lay, but I have a vague memory that it was related to the method currying that Django does behind the scenes when models are loaded.
#
robbie: I don't have any experience with oldforms, but the first line of code should make it clear that this applies to newforms, where it's been tested and used.
#
Why not just create a function? Something like this:
So instead of:
You'll only have to use:
#
Instead of:
Only use:
Otherwise one blank option is shown in dropbox.
#