I’m very new to Django so apologies in advance if this is an obvious problem, I have been through docs and numerous blog posts etc. but not getting anywhere fast so hoping someone can help here. I feel like my requirement is relatively straight forward so hopefully I’m just missing something obvious. This is a bit long winded too, trying to give as much info as possible, so again, apologies.
I was hoping to be able to create a “model” which acts as a parent to the User model, for example, each User is a member of a department. The available Departments are stored in a separate Department model. The Department ID will be part of the User model and have an FK relationship to the Department model, manyToOne - since a Department can have many users, essentially a parent table to User. I want to ensure users cannot be created unless a pre-existing Department is selected.
I also have the requirement to use Email address as the Username. So to this end, I have created a custom user model as per the docs: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-user
The custom model is all working fine, I can add a user with email address as the username and some other simple extra attributes like phone number, so I know that is OK.
I then tried to implement my Department bit, so I have defined a simple model like this;
department_name = models.CharField(max_length=150, unique=True)
Then in my custom User model I have the below additional field defined:
department = models.ForeignKey(Department, on_delete=models.PROTECT)
This all hung together OK when making migrations and I can see the FK relationship in my DB:
In my custom user creation form I have a ChoiceField which fetches the data from Departments to provide the available options, all good so far.
Now for the issue, when I try to submit the data for a new user it fails with:
Cannot assign “‘1’”: “User.department” must be a “Department” instance.
Inside the “create_user” function of my custom User model I have added this to fetch the company instance based on the passed in ID from the form, but it hasn’t helped;
company = Company.objects.get(pk=company_id)
user = self.model(
Am I trying to do something fundamentally bad / impossible here? Or have a I just missed some steps? I’ve googled a lot and cannot find any examples of what I am trying to achieve.
If any other info would be useful please let me know or if I have misplaced this question let me know where I should be asking.