Hi there,
I am new to Django and I was creating an e-commerce store using Django. I successfully created User Login Form which works perfectly, but I am stuck at User Registration Form. It is not being valid.
My forms.py:
from django import forms
from django.forms.widgets import PasswordInput
class UserLoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class UserRegistrationForm(forms.Form):
username = forms.CharField()
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)
def clean(self):
data = self.cleaned_data
password = self.cleaned_data.get('password')
password2 = self.cleaned_data.get('password2')
if password2 != password:
raise forms.ValidationError("Passwords must match")
return data
My register.html
<div>
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Register">
</form>
</div>
My login.html
<div>
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Login">
</form>
</div>
My views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
from .forms import UserLoginForm, UserRegistrationForm
# Create your views here.
def userRegistrationPage(request):
form = UserRegistrationForm()
context = {
'form': form
}
if request.method == 'POST':
form = UserRegistrationForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
print(username, password)
else:
print("Form is not valid")
return render(request, 'index/register.html', context)
def userLoginPage(request):
form = UserLoginForm()
context = {
'form': form
}
if request.method == 'POST':
form = UserLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(request, username=username, password=password)
print(user)
if user is not None:
login(request, user)
# Redirect to a success page.
return redirect("/")
else:
print("Error")
return render(request, 'index/login.html', context)
My urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="index-page"), # Home Page
path('register', views.userRegistrationPage, name='register'), #User Registeration Page
path('login', views.userLoginPage, name='login'), #User Login Page
]
Everytime I visit localhost:8000/register
, I get the message Form is not valid
from the if/else condition on form validation in views.py
. I did similar process with UserLoginForm
and that is working perfectly. Can somebody help me why the form is not being valid? What wrong I am doing? Much appreciated.