Creating a Unique Email Field Using Django Admin

There was almost the same question: How to make the email field unique in the User model from contrib.auth in Django

The solution was not perfect: email confirmation for uniqueness. The proposed solution is pretty funny. It prohibits changes for the User, leaving an intact email address. How to fix it? Thanks in advance!

+7
django django-admin django-forms
source share
3 answers

Thanks to Ofri Raviva, but what I saw is not what I need. So I solved my problem, and now I would like to share some tips:

  • Use your username instead of email, excluding email from the form. Underline its label as email.

  • Subclass user and create a UNIQUE field that receives email addresses, disguises it as email, excludes the original email field from the form.

It is simple but took some time. Hope this helps others with the same need.

+2
source share

in __init__.py

 from django.contrib.auth.models import User User._meta.get_field_by_name('email')[0]._unique = True 
+17
source share

This method will not make the email field unique at the database level, but worth a try.

Use custom validator :

 from django.core.exceptions import ValidationError from django.contrib.auth.models import User def validate_email_unique(value): exists = User.objects.filter(username=value) if exists: raise ValidationError("Email address %s already exits, must be unique" % value) 

Then in forms.py:

 from django.contrib.auth.models import User from django.forms import ModelForm from main.validators import validate_email_unique class UserForm(ModelForm): #.... email = forms.CharField(required=True, validators=[validate_email_unique]) #.... 
0
source share

All Articles