Django 3.x-自定义下拉菜单的自定义默认值

问题描述 投票:0回答:2

我自己构建了一个下拉类别选择菜单,以使django站点的搜索功能更加精确和过滤。到目前为止,它的工作情况还算不错,但是我无法弄清楚如何更改下拉菜单的默认值,因为它当前显示的是“ --------”,而不是“ All”(默认)值。

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'

app.css:

.my-custom-dropdown {
    position: relative;
    display: inline-block;
    vertical-align: middle;
    margin: 1.25%;
    max-width: 150px;
    width: 110px;
}

.my-custom-dropdown select {
    background-color: #cdcdcd;
    min-height: 40px;
    color: #000000;
    padding: .55em;
    padding-right: 2.5em;
    border: 0;
    margin: 0;
    max-width: 150px;
    width: 110px;
    border-radius: 3px;
    text-indent: 0.01px;
    -webkit-appearance: none;
    -moz-appearance: none;
}

.my-custom-dropdown::before,
.my-custom-dropdown::after {
    content: "";
    position: absolute;
    pointer-events: none;
}

.my-custom-dropdown::after {
    content: "\25BC";
    height: 1em;
    font-size: .625em;
    line-height: 1;
    right: 1.2em;
    top: 50%;
    margin-top: -.5em;
}

.my-custom-dropdown::before {
    width: 2em;
    right: 0;
    top: 0;
    bottom: 0;
    border-radius: 0 3px 3px 0;
}

.my-custom-dropdown select[disabled] {
    color: rgba(0, 0, 0, .3);
}

.my-custom-dropdown select[disabled]::after {
    color: rgba(0, 0, 0, .1);
}

.my-custom-dropdown::before {
    background-color: rgba(0, 0, 0, .15);
}

.my-custom-dropdown::after {
    color: rgba(0, 0, 0, .4);
}

做某事。有什么想法可以做到吗?使用content:我的CSS上的参数只有非常有限的bennefit,因为标签“ All”总是放在实际选择框之外。

感谢阅读:)

python django dropdown
2个回答
0
投票

您可以添加initial

您的表单

name = forms.CharField(initial='Your name')

0
投票

如果类别是Post模型中的一个选择字段,并且其中一个选项是'All',那么您可以像这样将类别的初始值设置为'All'

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'
© www.soinside.com 2019 - 2024. All rights reserved.