How do you pass the value of user_type (in CustomUser model) passed to a model form?

98 Views Asked by At

I have gone through many Q&As in SO and tried out various solutions. But I'm not sure whether the issue is with the form (CustomUserForm or StaffCreateForm--neither solves this problem), the view, or the way the user_type is set up. Any pointer is greatly appreciated.

The CustomUser model lists 3 user_types. The form displays a dropdown menu with the 3 choices. Regardless of my choice, I get an error: Select a valid choice. 2 is not one of the available choices.

How do I pass the value to be saved by the form?

#models.py

class CustomUser(AbstractUser):
    user_type_data = ((1, "HOD"), (2, "Staff"), (3, "Student"))
    user_type = models.CharField(default=1, choices=user_type_data, max_length=10)

#views.py

class StaffCreateView(CreateView):
    model = Staff
    form_class = StaffCreateForm
    context_object_name = 'staff'
    success_url = reverse_lazy('staff_list')

#forms.py

class CustomUserCreateForm(UserCreationForm): 
    class Meta:
        model = CustomUser
        fields = UserCreationForm.Meta.fields
        fields = ('user_type', 'username', 'email', 'first_name', 'last_name', 'subject')
    
    subject = forms.ModelMultipleChoiceField(
        queryset=Subject.objects.all(),
        widget=forms.CheckboxSelectMultiple
      )
class StaffCreateForm(CustomUserCreateForm):
    model = Staff

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['subject'].queryset = Subject.objects.all()
        self.fields['user_type'].initial = "2"

When I used "Inspect Elements" in the browser, the choice field looks right:

<select name="user_type" class="select" id="id_user_type"> <option value="1">HOD</option> <option value="2" selected="">Staff</option> <option value="3">Student</option>

</select>
<option value="1">HOD</option>
<option value="2" selected="">Staff</option>
<option value="3">Student</option>
<select name="user_type" class="select" id="id_user_type"> <option value="1">HOD</option> <option value="2" selected="">Staff</option> <option value="3">Student</option>
</select>
0

There are 0 best solutions below