Home > Enterprise >  How can i show error message for the user when using Email already exists
How can i show error message for the user when using Email already exists

Time:01-15

I'm using the Django framework. And I'm attempting to show an error message when the user registers and uses the username and/or email that already exists on a website. But the problem is when a user registers a new username and email, the system is not registered in a database. How can solve this problem? The error message: enter image description here

forms.py :


class RegisterUserForms(UserCreationForm):
    class Meta:
        model = User
        fields = ['username','email','password1','password2']
        widgets = {
            'email':forms.EmailInput(attrs = {
                'required' : True,
                'placeholder' : '[email protected]',
                'autofocus' : True,
                'name':'email',
            }),
            
            'username':forms.TextInput(attrs = {
                'required' : True,
            })
        }
        def __init__(self, *args, **kwargs):
            super(RegisterUserForms, self).__init__(*args, **kwargs)
            self.fields['password1'].widget.attrs={'placeholder': 'Password from numbers and letters of the Latin alphabet'}
            self.fields['password2'].widget.attrs={'placeholder': 'Password confirmation'}
    def clean_username(self):
        username_input = self.cleaned_data.get('username')
        if User.objects.filter(username=username_input ).exists():
            raise forms.ValidationError("username already exists!")

    def clean_email(self):
        email_input = self.cleaned_data.get('email')
        if User.objects.filter(email=email_input).exists():
            raise forms.ValidationError("email already exists!")

views.py:

def registerpage(request):
    form = RegisterUserForms()

    if request.method == 'POST':
        try:
            form = RegisterUserForms(request.POST)
            if form .is_valid():
                user = form.save()
                login(request, user)
                return redirect('login')
        except Exception as e:
            print(e)
            raise
    context = { # dictionary
        'form': form
    }
    return render(request, r'user\register.html', context)

register.html :



<body>
    <div  style="text-align: right;" >
        <h2  >register</h2> 
        <form method="POST" >
            {% csrf_token %}
            <div >
                <label for="{{form.email.id_for_label}}"> Email : </label>
                {{form.email}}
                <span >{{form.email.errors}}</span>
            </div>

            <div >
                <label for="{{form.username.id_for_label}}"> Username </label>
                {{form.username}}
                <span >{{form.email.errors}}</span>
            </div>

            <div >
                <label for="{{form.password1.id_for_label}}">password
                    </label>
                {{form.password1}}
            </div>
            
            <div >
                <label for="{{form.password2.id_for_label}}">confirem password</label>
                {{form.password2}}
            </div>

  


            <input type="submit" value="register" >

        </form>


{% endblock %}

CodePudding user response:

As it is shown in the docs, you need to return a value from your clean methods. This could be the issue you're experiencing.

So:

def clean_username(self):
    username_input = self.cleaned_data.get('username')
    if User.objects.filter(username=username_input ).exists():
        raise forms.ValidationError("username already exists!")
    
    return username_input
def clean_email(self):
    email_input = self.cleaned_data.get('email')
    if User.objects.filter(email=email_input).exists():
        raise forms.ValidationError("email already exists!")

    return email_input

Also, in your HTML for both fields you're showing errors for the email field. I think this needs change too:

<div >
    <label for="{{form.username.id_for_label}}"> Username </label>
    {{form.username}}
    <span >{{form.username.errors}}</span>
</div>
  • Related