Im trying to create a registration form in django but it says the account has been made client side but it wont let me login in witht the account i just made. i check the django admin database the user i just created does not exist there. here the codes
register.html
{% extends "base.html" %}
{% block content %}
{% include 'navbar.html' %}
<style>
.errorlist {
color: red;
}
</style>
<div class="container" style="padding-top: 110px; padding-bottom: 100px;">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-body">
<h2 class="text-center">Register</h2>
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
<form method="POST" class="form-group" id="registerForm">
{% csrf_token %}
<div class="form-group mb-3">
<input type="text" name="username" class="form-control" placeholder="Username (only letters, numbers, and @/./+/-/_ characters)" required>
{% if register_form.username.errors %}
<div class="errorlist">{{ register_form.username.errors }}</div>
{% endif %}
</div>
<div class="form-group mb-3">
<input type="text" name="first_name" class="form-control" placeholder="First Name" required>
{% if register_form.first_name.errors %}
<div class="errorlist">{{ register_form.first_name.errors }}</div>
{% endif %}
</div>
<div class="form-group mb-3">
<input type="text" name="last_name" class="form-control" placeholder="Last Name" required>
{% if register_form.last_name.errors %}
<div class="errorlist">{{ register_form.last_name.errors }}</div>
{% endif %}
</div>
<div class="form-group mb-3">
<input type="email" name="email" class="form-control" placeholder="Email" required>
{% if register_form.email.errors %}
<div class="errorlist">{{ register_form.email.errors }}</div>
{% endif %}
</div>
<div class="form-group mb-3">
<input type="password" name="password1" id="password1" class="form-control" placeholder="Password" required>
<div id="password1Error" style="color: red;"></div>
{% if register_form.password1.errors %}
<div class="errorlist">{{ register_form.password1.errors }}</div>
{% endif %}
</div>
<div class="form-group mb-3">
<input type="password" name="password2" class="form-control" placeholder="Confirm Password" required>
{% if register_form.password2.errors %}
<div class="errorlist">{{ register_form.password2.errors }}</div>
{% endif %}
</div>
<div class="form-check mb-3">
<input type="checkbox" class="form-check-input" id="termsAndConditions" name="termsAndConditions" required>
<label class="form-check-label" for="termsAndConditions">
I accept the <a href="{% url 'terms_and_conditions' %}">terms and conditions</a>
</label>
</div>
<p>Already have an account? <a href="{% url 'login' %}">Log In Now</a></p>
<button type="submit" class="btn btn-primary">Register</button>
</form>
<script>
document.getElementById('registerForm').addEventListener('submit', function(event) {
var password1 = document.getElementById('password1');
var password1Error = document.getElementById('password1Error');
// Clear previous error message
password1Error.textContent = '';
// Perform validation
if (password1.value.length < 8) {
// Prevent form from being submitted
event.preventDefault();
// Display error message
password1Error.textContent = 'Password must be at least 8 characters long.';
// Keep form data
var formData = new FormData(event.target);
password1.value = formData.get('password1');
}
});
</script>
</div>
</div>
</div>
</div>
</div>
{% include 'endpage.html' %}
{% endblock %}
views.py
from django.shortcuts import render, redirect
from .forms import RegistrationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.core.mail import send_mail
import random
from django.contrib import messages
import traceback
from django.http import JsonResponse
from .forms import LoginForm
from django.conf import settings
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from .forms import ProfilePictureForm
from .forms import RegistrationForm
from django.contrib.auth.views import PasswordChangeView
from django.urls import reverse_lazy
from django.contrib import messages
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
try:
user = form.save()
messages.success(request, 'Your account was created successfully.')
return redirect('home')
except Exception as e:
messages.error(request, f'An error occurred: {e}')
else:
messages.error(request, 'There was an error with your form.')
else:
form = RegistrationForm()
return render(request, 'register.html', {'register_form': form})
def login_request(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username_or_email = form.cleaned_data.get("username_or_email")
password = form.cleaned_data.get("password")
# Try to authenticate with username
user = authenticate(username=username_or_email, password=password)
# If user is None, try to authenticate with email
if user is None:
try:
user = User.objects.get(email=username_or_email)
user = authenticate(username=user.username, password=password)
except User.DoesNotExist:
pass
if user is not None:
login(request, user)
return redirect("home") # replace with your success url
else:
form.add_error(None, "Invalid username/email or password")
else:
form = LoginForm()
return render(request, "login.html", {"form": form})
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.contrib.auth import password_validation
import re
from .models import CustomUser
class RegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text = 'Required')
class Meta:
model = CustomUser
fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2', )
def clean_username(self):
username = self.cleaned_data.get('username')
if CustomUser.objects.filter(username=username).exists():
raise ValidationError("Username already exists")
return username
def clean_first_name(self):
first_name = self.cleaned_data.get('first_name')
if not re.match("^[A-Za-z]*$", first_name):
raise ValidationError("First name should only contain letters")
return first_name
def clean_last_name(self):
last_name = self.cleaned_data.get('last_name')
if not re.match("^[A-Za-z]*$", last_name):
raise ValidationError("Last name should only contain letters")
return last_name
def clean(self):
return super().clean()
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
print(f'Saving user: {user.username}, {user.email}, {user.first_name}, {user.last_name}')
if commit:
user.save()
return user
urls.py
"""
URL configuration for HealthAdviceGroup project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app1 import views
from app1.views import register
from app1.views import login_request
from django.contrib.auth import views as auth_views
from app1.views import MyPasswordChangeView
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('register/', views.register, name='register'),
path('login/', login_request, name='login'),
path('password_reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html'), name='password_reset'),
path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'),
path('profile/', views.profile, name='profile'),
path('logout/', views.logout_view, name='logout'),
path('password_change/', MyPasswordChangeView.as_view(), name='password_change'),
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html'), name='password_change_done'),
path('terms_and_conditions/', views.terms_and_conditions, name='terms_and_conditions'),
]