Home > Software engineering >  How to show error messages during registration?
How to show error messages during registration?

Time:10-18

How to show error messages during registration? I tried to make an error message when filling out a field of registration. But it does not work. that is, when I enter the wrong data, the error message does not appear . what could be the problem? and how to fix it??

forms.py

class UserRegistrationForm(forms.ModelForm):
    
    class Meta:
        model = User
        fields = ("username", "email", "password", )

    def clean_username(self):
        username = self.cleaned_data.get('username')
        model = self.Meta.model
        user = model.objects.filter(username__iexact=username)
        
        if user.exists():
            raise forms.ValidationError("A user with that name already exists")
        
        return self.cleaned_data.get('username')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        model = self.Meta.model
        user = model.objects.filter(email__iexact=email)
        
        if user.exists():
            raise forms.ValidationError("A user with that email already exists")
        
        return self.cleaned_data.get('email')


    def clean_password(self):
        password = self.cleaned_data.get('password')
        confim_password = self.data.get('confirm_password')
        
        if password != confim_password:
            raise forms.ValidationError("Passwords do not match")

        return self.cleaned_data.get('password')

views.py

def register_user(request):
    form = UserRegistrationForm()
    
    if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data.get('password'))
            user.save()
            messages.success(request, "Registration sucessful")
            return redirect('login')
    
    context = {
        "form": form
    }
    return render(request, 'registration.html')

registration.html

 <fieldset>
                            <input name="username"  type="text" id="username_id" placeholder="Your username" >
                            <p >{{form.username.errors}}</p>
                          </fieldset>
                        </div>
                        <div >
                            <fieldset>
                              <input name="email" type="email" id="email_id" placeholder="Your email" >
                            <p >{{form.email.errors}}</p>
                            </fieldset>
                          </div>
                          <div >
                            <fieldset>
                              <input name="password" type="password" id="password_id" placeholder="Your password" >
                              <p >{{form.password.errors}}</p>
                            </fieldset>

CodePudding user response:

As is discussed in the rendering fields manually section of the documentation,

for the fields you should also render {{ field.errors }}, and the {{ form.non_field_errors }} which deals with errors not specific to one form.

The template thus should look like:

<form action= "" method="post">
  {% csrf_token %}
  {{ form.non_field_errors }}
  {% for field in form %}
    <p>
      {{ field.errors }}
      {{ field.label }}
      {{ field }}
    </p>
  {% endfor %}
  <button type="submit" >Create User</button>
</form>

The section also discusses how to enumerate over the errors, and apply certain styling to these errors.

This answered before by @Willem Van Onsem

CodePudding user response:

since you are using ValidationError then you can display this in views:

if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data.get('password'))
            user.save()
            messages.success(request, "Registration sucessful")
            return redirect('login')
        else:
            messages.error(request, form.errors) # Innovation
  • Related