I’m trying to build my first custom user model extending AbstractUser as MyUser which then has a OneToOne relationship with my Employee class (and, later, with other classes such as Contractor). I’m using GCBV, and creating and displaying a new employee work as expected but the update form contains the correct fields but they are empty and I don’t understand why.
The database contains the expected data from the create.
I have other GCBVs working with full CRUD for classes without the user connection so I hoped that I understood enough to get the user part working - clearly not! Do I need to do something extra for Update that isn’t needed for Create or for non-user-related models?
Any help would be much appreciated - this is my first post here so I hope that I have provided enough detail:
models.py
class MyUser( AbstractUser ):
# Uses username, first_name, last_name and email from AbstractUser
is_employee = models.BooleanField( default = False, verbose_name=_('Staff'))
is_contractor = models.BooleanField( default = False, verbose_name=_('Contractor'))
class Employee( models.Model ):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, # MyUser
on_delete=models.CASCADE,
related_name='employee',
)
is_staff_admin = models.BooleanField( default=False, null=True, verbose_name=_('Administrator') )
views.py
class EmployeeUpdateView( UpdateView ):
model = Employee
pk_url_kwarg = 'employee_pk'
template_name = 'employees/employee_create_and_update.html'
form_class = EmployeeChangeForm
success_url = None
context_object_name = 'employee'
forms.py
class MyUserChangeForm( UserChangeForm ):
class Meta:
model = get_user_model() # MyUser
fields = (
# AbstractUser fields
'username',
'email',
'first_name',
'last_name',
# MyUser fields
# None yet - is_employee is not visible on the form
)
class EmployeeChangeForm( MyUserChangeForm ):
class Meta( MyUserChangeForm.Meta ):
model = MyUser
templates/employees/employee_create_and_update.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form method='POST'>
{% csrf_token %}
{{ form|crispy }}
{% include "create_update_buttons_snippet.html" %}
</form>
{% endblock %}
urls.py
…
path( 'employee/update/<int:employee_pk>/', EmployeeUpdateView.as_view(), name='employee_update' ),
...