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>
Your form specifies
fields = '__all__', which includesStaff.adminone-to-one field. TheStaffForm.first_nameandStaffForm.last_nameoverride the formfield for those model fields, but aren't strictly why those fields are present on the form.If you want to remove the
adminfield fromStaffFormyou should replacefields = '__all__'withfields = ['first_name', 'last_name']orexclude = ['admin'].You can read more on the Django docs for selecting model form fields.