gpt4 book ai didi

django - ModelChoiceField 小部件属性无效

转载 作者:行者123 更新时间:2023-12-05 09:15:52 26 4
gpt4 key购买 nike

我有一个必须手动呈现的模型表单,但 ModelChoiceField 属性没有任何效果。

class ExtendedUserForm(forms.ModelForm):
favourite_provider = forms.ModelChoiceField(queryset=Provider.objects.all())

class Meta:
EXPERTISE_CHOICES = (
('N', 'Novice'),
('B', 'Beginner'),
('I', 'Intermediate'),
('E', 'Expert'),
)

model = ExtendedUser
labels = {
'expertise': 'Expertise',
'favourite_provider': 'Favourite provider',
'job_title': 'Job title',
'job_place': 'Company/Institution',
}

widgets = {
'expertise': forms.Select(choices=EXPERTISE_CHOICES, attrs={'class': 'form-control'}),
'favourite_provider': forms.Select(attrs={'class': 'form-control'}),
'job_title': forms.TextInput(attrs={'placeholder': 'Your job title', 'class': 'form-control'}),
'job_place': forms.TextInput(attrs={'placeholder': 'Your company/institution', 'class': 'form-control'}),
}
exclude = ['user', 'history', 'favourite_services']

渲染后的 HTML 如下:

<div class="form-group">
<label><label for="id_expertise">Expertise:</label></label>
<select name="expertise" required id="id_expertise" class="form-control">
<option value="" selected>---------</option>
<option value="N">Novice</option>
<option value="B">Beginner</option>
<option value="C">Competent</option>
<option value="P">Proficient</option>
<option value="E">Expert</option>
</select>
</div>


<div class="form-group">
<label><label for="id_favourite_provider">Favourite provider:</label></label>
<select name="favourite_provider" required id="id_favourite_provider">
<option value="" selected>---------</option>
<option value="1">AWS</option>
</select>

如您所见,第二个选择没有 class 属性,尽管我在这里明确指出 'favourite_provider': forms.Select(attrs={'class': 'form-control'})。如何解决?

最佳答案

Django documentation引用(来自笔记):

Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically.

要得到你想要的东西,你应该明确填写 ModelChoiceField 的小部件参数:

favourite_provider = forms.ModelChoiceField(queryset=Provider.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))

关于django - ModelChoiceField 小部件属性无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51642393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com