Custom User model with different roles simultaneously

I’ve been trying to create the models for my application but I run to this issue :slight_smile: i
I want to create a user with multiple roles simultaneously. when I create an account in the user model with the role of teacher and admin .the instances are not created in the Teacher and Admin models
models.py*

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.fields.related import ForeignKey
from django.utils.translation import gettext as _

# Create your models here.
class Role(models.Model):
  STUDENT = 1
  TEACHER = 2
  SECRETARY = 3
  SUPERVISOR = 4
  ADMIN = 5
  ROLE_CHOICES = (
      (STUDENT, 'student'),
      (TEACHER, 'teacher'),
      (SECRETARY, 'secretary'),
      (SUPERVISOR, 'supervisor'),
      (ADMIN, 'admin'),
  )

  id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True)

  def __str__(self):
      return self.get_id_display()

class User(AbstractUser):
    roles = models.ManyToManyField(Role)
    username = models.CharField(max_length = 50, blank = True, null = True, unique = True)
    email = models.EmailField(_('email address'), unique = True)
    native_name = models.CharField(max_length = 5)
    phone_no = models.CharField(max_length = 10)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
    def __str__(self):
        return "{}".format(self.email)

class Etudiant(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    address = models.CharField(max_length = 50, blank = True, null = True)

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    profession = models.CharField(max_length = 50, blank = True, null = True)

class Admin(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    maman = models.CharField(max_length = 50, blank = True, null = True)

admin.py

from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from accounts.models import  Etudiant, Teacher, User,Role,Admin
from django.contrib.auth.forms import UserChangeForm

admin.site.site_header = 'Scientific Journal Admin'
admin.site.site_title = 'Scientific Journal '
admin.site.site_url = 'http://Scientific+Jounal.com/'
admin.site.index_title = 'Scientific Journal administration'
admin.empty_value_display = '**Empty**'

class UserAdmin(BaseUserAdmin):
  form = UserChangeForm
  fieldsets = (
      (None, {'fields': ('email', 'password', )}),
      (_('Personal info'), {'fields': ('first_name', 'last_name' , 'roles')}),
      (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                     'groups', 'user_permissions')}),
      (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
        (_('user_info'), {'fields': ('native_name', 'phone_no')}),
  )
  add_fieldsets = (
      (None, {
          'classes': ('wide', ),
          'fields': ('email', 'password1', 'password2'),
      }),
  )
  list_display = ['email', 'first_name', 'last_name', 'is_staff', "native_name", "phone_no"]
  search_fields = ('email', 'first_name', 'last_name')
  ordering = ('email', )
admin.site.register(User, UserAdmin)
admin.site.register(Role)
admin.site.register(Etudiant)
admin.site.register(Admin)
admin.site.register(Teacher)

That’s because you don’t have anything in your model admin to create those ancillary relationship entries. This isn’t something that would happen “automatically”, you need to make it happen.

You could do something like override the save_model method in your ModelAdmin class to determine whether or not the Teacher and Admin instances need to be created (or deleted) and then manage those model instances.

2 Likes

I have the same problem can give a simple explanation cause it’s my first try with django

Please be more specific with the issue you’re facing.

Note how the original posting detailed what they were trying to do, the code they had written to accomplish that, and an explanation as to what was or wasn’t happening.

That was a very well-written question. It’s that level of detail that made it possible for me to supply something other than just a vague answer or a list of questions requiring further clarification.

Also, unless your question really is exactly the same issue, I’d suggest you open up a different topic to discuss it. It’s more helpful to keep the discussion topics focused on one issue.

1 Like

I am working in an academic project to build a scientific journal with multiple roles authors reviewers and editors and each user can have more than one roles to implement this I follow thistutorial. but I got the same problem that khalid get and now I am looking for a way to build a strategy to implement those roles in django


this is the diagram class for users and roles
i hope it’s clear now
thank you

So if you have the same issue as presented above (creating the User doesn’t automatically create the related role entity), then my answer is the same - at whatever point you assign the roles to the User, you would also create the appropriate related objects. (You would also want to handle the situation where a role was removed, therefore possibly making it appropriate to delete that entity.)

1 Like

if you could please elaborate more , I’m not a Django expert and I will be more than grateful for your assistance.

Where are you having problems? You’ve got the tutorial that you’ve referenced earlier, and the sample code as part of the original message here. You’re going to need to be a lot more specific as to exactly what you need help with for me to be able to provide assistance.

1 Like