Reputation: 79
When I compile my code, this error message is returned:
'ModelChoiceField' object has no attribute 'to_field_name'
ModelChoiceFiled is in the 'school_code' field.
I already type to_field_name.
class UserRegister(forms.ModelForm):
class Meta:
mstSchool = MstSchool.objects.filter(use_yn__exact="Y").order_by("code")
model = MstUser
fields = [ 'name', 'id', 'password', 'school_code']
widgets = {
'id' : forms.TextInput(attrs={'placeholder' : 'User ID', 'class':'form-control'}),
'password' : forms.TextInput(attrs={'placeholder' : 'password', 'class':'form-control school-password', 'type':'password'}),
'name' : forms.TextInput(attrs={'placeholder' : 'name', 'class':'form-control school-name'}),
'school_code' : forms.ModelChoiceField(queryset=MstSchool.objects.filter(use_yn__exact="Y").order_by("code"), empty_label="(Nothing)", to_field_name="school_code")
}
'ModelChoiceField' object has no attribute 'to_field_name'
Upvotes: 3
Views: 1696
Reputation: 477685
You are confusing fields and widgets. A ModelChoiceField
is not a widget, but a form field:
class UserRegister(forms.ModelForm):
school_code = forms.ModelChoiceField(queryset=MstSchool.objects.filter(use_yn__exact="Y").order_by("code"), empty_label="(Nothing)")
class Meta:
model = MstUser
fields = [ 'name', 'id', 'password', 'school_code']
widgets = {
'id' : forms.TextInput(attrs={'placeholder' : 'User ID', 'class':'form-control'}),
'password' : forms.TextInput(attrs={'placeholder' : 'password', 'class':'form-control school-password', 'type':'password'}),
'name' : forms.TextInput(attrs={'placeholder' : 'name', 'class':'form-control school-name'}),
}
Please do not set the id
and the password
through the ModelForm
. Passwords should be hashed, and usually the set_password
method [Django-doc] is used for that.
Upvotes: 3