我有必须手动呈现的这种模型形式,但是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'})
进行了修正。如何解决?
答案 0 :(得分:1)
Django documentation的引号(来自注释):
以声明方式定义的字段按原样保留,因此任何 对元属性(例如小部件,标签, help_texts或error_messages被忽略;这些仅适用于字段 它们是自动生成的。
要获得所需的内容,应显式填充ModelChoiceField的小部件参数:
@IBAction func buttonName(_ sender: UIButton) {
sender.isUserInteractionEnabled = false
// Do whatever you need to do after...
}