How to make email field unique in model User from contrib.auth in Python Django?

Sometimes, we want to make email field unique in model User from contrib.auth in Python Django.

In this article, we’ll look at how to make email field unique in model User from contrib.auth in Python Django.

How to make email field unique in model User from contrib.auth in Python Django?

To make email field unique in model User from contrib.auth in Python Django, we can use the get_field method.

For instance, in models.py, we write

from django.contrib.auth.models import User

User._meta.get_field('email')._unique = True

to get the email field with User._meta.get_field('email').

And then we set its _unique property to True.

Conclusion

To make email field unique in model User from contrib.auth in Python Django, we can use the get_field method.