I am trying to set up a custom user model using email as the USERNAME_FIELD. I want to have the ability to have multiple users with the same email as long as only one of them is not soft deleted.
I though that using UniqueConstraint would achieve this, however I have tested it by creating users and soft deleting them and then attempting to create a new user with the same email. However, the user is not created. Also there is no exception that seems to be raised.
Any help would be appreciated, I’m not sure if my understanding of UniqueConstraint is wrong and it was not meant to do what I am attempting to do, or that because email is being used as the USERNAME_FIELD this creates additional complications.
models.py
class User(AbstractUser):
username = None
email = models.EmailField(unique=True)
is_deleted = models.BooleanField(default=False)
USERNAME_FIELD ="email"
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return str(self.email)
class Meta:
constraints =[
models.UniqueConstraint(
fields=["email"],
condition=Q(is_deleted=False),
name="unique_active_email"
)
]
forms.py
class UserCreateForm(UserCreationForm):
class Meta:
model = User
fields = ("email", "password1", "password2")
views.py
def register(request):
if request.method == "POST":
form = UserCreateForm(request.POST)
if form.is_valid():
form.save()
return redirect("register")
context = {"form": UserCreateForm}
return render(request, 'register.html', context)