Where does this (Django) CustomUser field come from?

30 Views Asked by At

My searches only turned up tips on how to add fields or add_fieldsets in admin.py when using Django's CustomUser. I need to find out where a field named admin comes from when the model form is rendered in the class-based CreateView. There is no error with the code, but the template automatically adds an admin choice field on top of the page-the drop-down choices are users (all 3 types) already created. But I want to create a new staff user. So how do I tell Django to leave the admin field out (at least until a user is saved)?

# 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)

class Staff(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    email = models.EmailField()
    objects = models.Manager()


# forms.py
class StaffForm(forms.ModelForm):
    model = Staff
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

    class Meta:
        model = Staff
        fields = '__all__'

# views.py
class StaffCreateView(CreateView):
    model = Staff
    form_class = StaffForm
    context_object_name = 'staff'
    success_url = reverse_lazy('staff_list')


# staff_form.html
<form method="post">
    {{ form.as_p }}
    <input type="submit" value="Save">
</form>
1

There are 1 best solutions below

2
On

Your form specifies fields = '__all__', which includes Staff.admin one-to-one field. The StaffForm.first_name and StaffForm.last_name override the formfield for those model fields, but aren't strictly why those fields are present on the form.

If you want to remove the admin field from StaffForm you should replace fields = '__all__' with fields = ['first_name', 'last_name'] or exclude = ['admin'].

You can read more on the Django docs for selecting model form fields.