darkhorse
darkhorse

Reputation: 8782

How to change the default selected option in a Django ChoiceField?

I am trying to get a form with a choice field in Django. My form code looks like this:

UNIVERSITIES = (
    ('North South University', 'North South University'),
    ('BRAC University', 'BRAC University'),
)

class SearchForm(forms.Form):
    """
    Form used to search for a professor.
    """
    professor_name = forms.CharField(
        label="Enter a professor's name or name code",
        max_length=255,
        widget=forms.TextInput(attrs={
            'placeholder': 'Search for a professor',
            'required' : 'required',
        }),
    )
    university = forms.ChoiceField(
        label="Select your university",
        choices=UNIVERSITIES,
    )

In the form I get 'North South University' by default. How do I change that to an empty string? That is, no option will be selected Thanks.

Upvotes: 0

Views: 4147

Answers (3)

Krumple
Krumple

Reputation: 66

Method 1: On ModelForm I use this method to replace all fields:

class SearchForm(forms.ModelForm):
    class Meta:
        model = models.Search
        fields = "__all__"
    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)
        for f in SearchForm.base_fields.values(): f.empty_label = f.label

Method 2: On ModelForm I use this method to replace only one field:

class SearchForm(forms.ModelForm):
    class Meta:
        model = models.Search
        fields = "__all__"
    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)
        self.fields['university'].empty_label = "Label"

Upvotes: 0

kushtrimh
kushtrimh

Reputation: 916

You can do something like this:

UNIVERSITIES = (
    ( None, ''),
    ('North South University', 'North South University'),
    ('BRAC University', 'BRAC University'),
)

Since the value will be None by default the user will be required to select one of the options. If you want to change the text to something like 'Select your university' you can change the '' to that or you can add a Label to the ChoiceField.

Upvotes: 2

marcusshep
marcusshep

Reputation: 1964

Try this:

university = forms.TypedChoiceField(
    label="Select your university",
    choices=UNIVERSITIES,
    empty_value="--- youre empty value here ---",
)

Upvotes: 3

Related Questions