On Sep 5, 11:19 am, Malcolm Tredinnick <
malc...@pointy-stick.com>
wrote:
> On Fri, 2008-09-05 at 03:11 -0700, mwebs wrote:
> > Hello,
>
> > I use amodelchoicefieldand want to remove the entry that represents
> > "no item selected"(<option value="">------</option>), because in my
> > scenario I will only allow to select between existing entries.
>
> Specify adefaultvalue for the field (one of the choices). Then that
> will be shown as the initially selected option.
I could not find a way to specify a default value.
> The empty choice isn't there because it's a valid option. It's actually
> a useful user-interface feature. If somebody submitted a form without
> making a choice, it would be invalid because the empty "----" choice is
> not valid. It's there because you didn't specify adefaultvalue and
> Django doesn't make a choice ofdefaultinitial value for you. The user
> has not yet made a selection, so they must choose one of the options
> explicitly. If they just hit "submit" without making a choice, Django is
> careful to ensure they don't accidentally end up selecting whichever
> option Django displayed first.
>
> Regards,
> Malcolm
Sounds reasonable. However I am using a RadioSelect widget in my "rite-
of-passage" first Django poll app. It looks very weird to see this on
a form (please forgive the crude ASCII art):
Vote Now:
* ----
* Yes
* No
[Submit]
However I looked at the django source code and found that you can set
empty_label to None to get rid of that first choice. Here is how I did
it in my form class:
from django import forms
from gpp.polls.models import Choice
class VoteForm(forms.Form):
"""Form for voting in a poll."""
options = forms.ModelChoiceField(queryset = Choice.objects.none(),
widget = forms.RadioSelect)
def __init__(self, poll_id):
super(VoteForm, self).__init__()
self.fields['options'].queryset =
Choice.objects.filter(poll=poll_id)
self.fields['options'].empty_label = None
I hope this helps someone!
Best,
BN