2

I know that superusers and regular users are both just django's User objects, but how can I write a custom user class that requires some fields for plain users and doesn't require those fields for superusers?

nmm9422
  • 31
  • 1

2 Answers2

1

No structure in the database is tricky. JSONFields for example may prove to be extremely hard to tame when the app grows.

I would go and try to make it "simple" - more maintainable (I imagine if you need to do stuff like that you may want to extend the model in the future). If this is a new project you can easily change the default user model. But that may or may not help you with your case.

You can always make two models:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser

class Mortal(AbstractBaseUser):
    is_superuser = False

    username = models.CharField(max_length=256)
    first_name = models.CharField(max_length=256)
    last_name = models.CharField(max_length=256)

class Admin(AbstractBaseUser):
    is_superuser = True

    username = models.CharField(max_length=256)

and then make your own authentication backend:

class MyBackend(object):
    """
    Danger! A backend to authenticate only via username
    """

    def authenticate(self, username=None):
        try:
            return Mortal.objects.get(username=username)
        except Mortal.DoesNotExist:
            try:
                return Admin.objects.get(username=username)
            except Admin.DoesNotExist:
                return None
McAbra
  • 2,382
  • 2
  • 21
  • 29
1

You can have a profile class (say UserProfile) with foreign key to the user that is to be created only when user signs up using the website's registration form. That way, superuser which is created on admin site or through command line wouldn't need an extra profile instance attached to it.

hurturk
  • 5,214
  • 24
  • 41