David Gardner
David Gardner

Reputation: 149

Form validation error not showing in the HTML page in Django

I am developing a simple sign up and sign in web application in Django. I am using Django form for the user inputs. I write the clean function in the forms.py file. If username already exist in the database it should display the error message in the HTML page but nothing display on the webpage, can someone find out the mistake in my code.

Here is my code:

view.py

def RegistrationView(request):
    form=Registration_Form()
    
    if request.method=='POST':
        
        form=Registration_Form(request.POST)
        if form.is_valid():

            form.save()
            return redirect('login_view')
        else:
            # messages.error(request,"Form is Invalid!")
            return redirect('registration_view')

    else:
        return render(request,'registration.html',{'form':form})

forms.py

from django import forms
from .models import User_Registration
class Registration_Form(forms.ModelForm):
    class Meta:
        model=User_Registration
        fields=('company_name','username','password','email')

        widgets={
            'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}),
            'username':forms.TextInput(attrs={'class':'form-control'}),
            'password':forms.PasswordInput(attrs={'class':'form-control'}),
            'email':forms.EmailInput(attrs={'class':'form-control'}),
        }
    def clean_username(self):
        user_name=self.cleaned_data['username']
        if User_Registration.objects.filter(username=user_name).exists():
            raise forms.ValidationError("Username Already Exist")

registration.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>



  {% if form.errors %}
  {% for field in form %}
      {% for error in field.errors %}
          <div class="alert alert-danger">
              <strong>{{ error|escape }}</strong>
          </div>
      {% endfor %}
  {% endfor %}
  {% for error in form.non_field_errors %}
      <div class="alert alert-danger">
          <strong>{{ error|escape }}</strong>
      </div>
  {% endfor %}
{% endif %}
  <div class="form-group">
    <br><br><br>
    <h2 style="padding-left: 480px;">Registration Form</h2>
    <br>



  <form method="POST" action="">

    {{form.as_p}}
    {% csrf_token %}


    <input type="submit" value="Submit">
  </form>
 
</div>
</body>
</html>

Upvotes: 0

Views: 923

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476758

You should not redirect in case the form is invalid, since then it will render a new page (with an empty form). You thus should not wrap the render(…) call in the else part of the if request.method == 'POST', since code paths with a POST request, can also result in re-rendering the template. You thus can rewrite the view to:

def RegistrationView(request):
    form=Registration_Form()
    if request.method == 'POST':
        form=Registration_Form(request.POST)
        if form.is_valid():
            form.save()
            # redirect only when the form is valid
            return redirect('login_view')
    # do not wrap the render(…) call in the else part
    return render(request,'registration.html',{'form':form})

Upvotes: 2

Related Questions