'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.



Solution 1:[1]

Try this:

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

Solution 2:[2]

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.

Solution 3:[3]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marcusshep
Solution 2
Solution 3