0

I'm writing a simple app, and I'm totally happy with Django User model, except that I want a user email to be unique and obligatory field. I have developed a solution, but I'm wondering if I'm missing something.

a) If you think that something is missing in the solution below please let me know

b) If you think that you have a better solution please share

This is what I did

  1. Created a custom user model

# customers/models.py

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

class User(AbstractUser):
    email = models.EmailField(verbose_name='Email', unique=True, blank=False, null=False)
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = ['email']

  1. Added AUTH_USER_MODEL = 'customers.User' to settings.py

  2. Changed a reference to User model:

   User = get_user_model()
  1. Modified admin.py in order to be able to add users using Django admin.
# customers/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model

User = get_user_model()

class CustomUserAdmin(UserAdmin):
    list_display = ('username', 'email', 'is_staff')

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2'),
        }),
    )

admin.site.register(User, CustomUserAdmin)
alv2017
  • 752
  • 5
  • 14
  • 1
    Does this answer your question? [Make User email unique django](https://stackoverflow.com/questions/53461410/make-user-email-unique-django) – markwalker_ Mar 21 '21 at 22:56
  • Not exactly, I want a bare minimum solution which ensures a unique email and non-broken django authentication system. – alv2017 Mar 21 '21 at 23:06
  • Minimum would be to ensure all user creation happens using the same form and that form does a query on the `User` table to ensure that the value of the `email` field in the form is unique against the database. – markwalker_ Mar 21 '21 at 23:07

1 Answers1

0

I hope this one you are looking for

Use the below code snippets in any of your models.py

models.py

from django.contrib.auth.models import User
User._meta.get_field('email')._unique = True

django version : 3.0.2

Reference : Django auth.user with unique email

https://stackoverflow.com/a/64075027/6651010

Jasir
  • 653
  • 8
  • 17