Search code examples
pythondjangodropdown

Django 3.x - Custom default value of a custom dropdown menu


I build a dropdown category selection menu myself to make the search function of my django site more preceise and filterd. This is working pretty fine so far but I was not able to figure out how I can change the default value of my dropdown menu as it's currently showing "--------" and not something like "All" as default selected value.

base.html:

<div class="my-custom-dropdown">
   <a>{{ categorysearch_form.category }}</a>
</div>

search_context_processor.py:

def categorysearch_form(request):
    form = SearchForm()
    return {'categorysearch_form': form}

forms.py

class SearchForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['category']

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(SearchForm, self).__init__(*args, **kwargs)
        self.fields['category'].required = False
        self.fields['category'].initial = 'All'

does smb. has any idea how this can be accomplished? using the content: parameter at my css only has a very limited bennefit as the lable "All" always gets placed outside of the actual selection box.

thanks for reading :)


Solution

  • The empty choice is displayed as "--------". To display something else (maybe "All") in place of "--------", we can add an empty_label in the ModelForms init method, like below -

    self.fields['category'].empty_label = "All"
    

    You can check this doc as well.