Jin-hyeong Ma
Jin-hyeong Ma

Reputation: 79

django ModelChoiceField, to_field_name

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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

Related Questions