51๐
You can use the โlazyโ function ๐
from django.utils.functional import lazy
class CarSearchForm(forms.Form):
# lots of fields like this
bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)())
very nice util function !
18๐
Try using a ModelChoiceField instead of a simple ChoiceField. I think you will be able to achieve what you want by tweaking your models a bit. Take a look at the docs for more.
I would also add that ModelChoiceFields are lazy
by default ๐
- [Django]-How can I correctly set DJANGO_SETTINGS_MODULE for my Django project (I am using virtualenv)?
- [Django]-How to add readonly inline on django admin
- [Django]-Docker app server ip address 127.0.0.1 difference of 0.0.0.0 ip
2๐
You can now just use (since I think Django 1.8):
class CarSearchForm(forms.Form):
# lots of fields like this
bodystyle = forms.ChoiceField(choices=bodystyle_choices)
Note the missing parenthesis. If you need to pass arguments, I just make a special version of the function with them hardcoded just for that form.
- [Django]-In django, how do I call the subcommand 'syncdb' from the initialization script?
- [Django]-How to get full url from django request
- [Django]-ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
1๐
Expanding on what Baishampayan Ghose said, this should probably be considered the most direct approach:
from django.forms import ModelChoiceField
class BodystyleChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return '%s (%s cars)' % (obj.bodystyle_name, obj.car_set.count()))
class CarSearchForm(forms.Form):
bodystyle = BodystyleChoiceField(queryset=Bodystyle.objects.all())
Docs are here: https://docs.djangoproject.com/en/1.8/ref/forms/fields/#modelchoicefield
This has the benefit that form.cleaned_data['bodystyle']
is a Bodystyle
instance instead of a string.
- [Django]-Django: How to rollback (@transaction.atomic) without raising exception?
- [Django]-Django substr / substring in templates
- [Django]-What is @permalink and get_absolute_url in Django?