Django auth.user with a unique email address

I am using the django.auth system and I have this:

class RegisterForm(UserCreationForm): username = forms.RegexField(label= "Username" , max_length = 30, regex = r'^[\w]+$', error_messages = {'invalid': "This value may contain only letters, numbers and _ characters."}) email = forms.EmailField(label = "Email") first_name = forms.CharField(label = "First name", required = False) last_name = forms.CharField(label = "Last name", required = False) class Meta: model = User fields = ("username", "first_name", "last_name", "email", ) def save(self, commit = True): user = super(RegisterForm, self).save(commit = False) user.first_name = self.cleaned_data["first_name"] user.last_name = self.cleaned_data["last_name"] user.email = self.cleaned_data["email"] if commit: user.save() return user 

I want to set up email as uniques and check the form for this check. How can i do this?

+6
source share
5 answers

add this to your form. But this is not an ideal way. race conditions are only available using this form. I recommend you add a unique db level restriction.

 def clean_email(self): data = self.cleaned_data['email'] if User.objects.filter(email=data).exists(): raise forms.ValidationError("This email already used") return data 

SQL to add a unique constraint:

 ALTER TABLE auth_user ADD UNIQUE (email) 
+9
source

Somewhere in your models:

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

Pay attention to the underscore before unique . Here, the information is actually stored. User._meta.get_field('email').unique is just a @property that looks at it.

This should also work for syncdb, so you will have consistency with the database.

Please note that from Django 1.5 you will not have to do such things, as the user model will connect.

+14
source

I'm not sure how to use this, but

 from django.contrib.auth.models import User User._meta.get_field_by_name('email')[0].unique=True 

must do it. I assume this applies to your .py models before running syncdb in the auth model. Booth to try it yourself.

+1
source

An override of the clean () method proposed by mumimo is described here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method

You can usually use unique = True in your field definition and then use ModelForm so that it automatically runs clean () for all fields in your form, but if you use the user class django.auth you cannot change the fields.

0
source

You can do the same using this in an abstract user model:

 class User(AbstractUser): ... class Meta: unique_together = ('email',) 
0
source

Source: https://habr.com/ru/post/886594/


All Articles