Home > Software design >  Check if email already exist in database
Check if email already exist in database

Time:11-18

In my django account app I want to check if inputed email exist in database (basic django db.sqlite3).

forms.py:

from django import forms
from django.contrib.auth.models import User


class UserRegistrationForm(forms.ModelForm):

    password = forms.CharField(label='Hasło', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Powtórz hasło', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'email')

    def clean_password2(self):
        cd = self.cleaned_data



        if cd['password'] != cd['password2']:
            raise forms.ValidationError('Hasła nie są identyczne.')

        return cd['password2']

views.py:

def register(request):
    if request.method == "POST":
        user_form = UserRegistrationForm(request.POST)

        if user_form.is_valid():
            # Creating new user object, without saving in database
            new_user = user_form.save(commit=False)

            # Setting new password
            new_user.set_password(
                user_form.cleaned_data['password'])

            # Saving user object
            new_user.save()
            return render(request,
                          'account/register_done.html',
                          {'new_user': new_user})
    else:
        user_form = UserRegistrationForm()

    return render(request,
                  'account/register.html',
                 {'user_form': user_form})

Now when i enter the same email for another user, form creates that user.

I think is it possible to make this in that way? 1). make email as variable like password and password2 2). remove email from meta 3). create method clean_email() with checking if email exist in db if not raise error

I don't know how to get to emails in db

Thanks for all help!

CodePudding user response:

Below is_valid(): in your views.py do this

if user_form.is_valid():
    new_user = user_form.save(commit=False)
    email=user_form.cleaned_data['email']
    if not User.objects.filter(email=email).exists():
        //the rest of your code 
    else:
       //some error message

This ensures that a new user is only created if they do not already exist.

If you working on an app that requires a username, email, and password length of x(in this case 8), then do this.

if not User.objects.filter(username=username).exists():
    if not User.objects.filter(email=email).exists():
        if len(password) < 8:
            // some error message alert 
            return('register') // the same page
        //continue with the rest of your code
        .....
    return ('login-page')
return('register') the same page

If this solves your issue please don't forget to accept this as the correct answer.

  • Related