[Django]-Unique together in Django User Model

0👍

AbstractUser is a mostly-complete model that defines a set of default fields, including username uniqueness. If that doesn’t work for you, then you should inherit from AbstractBaseUser instead and define the full set of fields.

0👍

Uniqueness on the username field is only if you use the built-in authentication backend.

Directly from the django docs

If you use the default authentication backend, then your model must have a single unique field…A non-unique username field is allowed if you use a custom authentication backend that can support it.

Django Custom Authentication

Hope this helps

👤Puches

0👍

From your question and the comments its pretty clear(if i am not fully misunderstood) that you want to save an user with an email (an identifier) with multiple platform. If this is the case, you can use a postgres ArrayField on your platform column if your database is Postgresql, or alternavely you can use JsonField provided by django.

  1. Postgresql Array Field available in django > 1.7

  2. Django Json Field

0👍

I might be too late to answer this but the solution I used recently for the same problem is:

class User(AbstractUser):
    platform_and_email = models.CharField(max_length=100, unique=True)
    username = models.CharField(max_length=20, blank=True, null=True)
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'platform_and_email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    class Meta:
        verbose_name = "App User"
        verbose_name_plural = "App Users"

You can use a single field and set it as unique. On the client side of your app you can authenticate user by doing ‘platform_’ + email behind the scenes.

You will also have to write your own custom backend and make it use your platform_and_email field to validate and authenticate.

Let me know if you need more explanation on this.

👤DEV

Leave a comment