When I create a new user account I set the terminal to print working if the create account form works and the terminal does that
but the created accounted doesn't show on django admin panel which means the account wasn't created and since the account wasn't created I don't get redirected to create profile page
my views.py
from django.shortcuts import redirect, render
from django.contrib.auth.models import User, auth
from django.http import HttpResponse
from django.contrib import messages
from .models import UserProfile
from .forms import UserRegistrationForm, UserProfileForm
from django.contrib.auth import login
from django.http import JsonResponse
from .models import Posts
from .models import Videos
# Create your views here.
def home(request):
post = Posts.objects.all()
video = Videos.objects.all()
return render(request,'Index.html',{'Home':'Title',
'Posts':post,
'Videos':video,})
def createAccount(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
profile_form = UserProfileForm(request.POST, request.FILES)
if user_form.is_valid() and profile_form.is_valid():
username = user_form.cleaned_data['username']
email = user_form.cleaned_data['email']
password = user_form.cleaned_data['password']
password2 = user_form.cleaned_data['password2'] # Add this line
if password != password2: # Check if passwords match
user_form.add_error('password2', 'Passwords do not match') # Add error message
elif User.objects.filter(username=username).exists():
user_form.add_error('username', 'This username is already taken.')
elif User.objects.filter(email=email).exists():
user_form.add_error('email', 'This email is already registered.')
else:
user = user_form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
login(request, user)
messages.success(request, 'Your account has been succesfully created!')
return redirect('createProfile')
else:
user_form = UserRegistrationForm()
profile_form = UserProfileForm()
print("working")
return render(request, 'createAccount.html', {'user_form': user_form, 'profile_form': profile_form, 'signUP':'Title'})
def createProfile(request):
if request.method == 'POST':
profile_form = UserProfileForm(request.POST, request.FILES, instance=request.user.userprofile)
if profile_form.is_valid():
profile_form.save()
return redirect('Homepage')
else:
profile_form = UserProfileForm(instance=request.user.userprofile)
return render(request, 'profilecreation.html', {'profile_form': profile_form, 'createProfile':'Title'})
def login(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
# Check if the user has a profile with required fields filled
try:
profile = user.userprofile
if profile.matricNumber and profile.Department and profile.faculty and profile.usertag:
return redirect('/') # Redirect to homepage if required fields are filled
else:
return redirect('create_profile') # Redirect to profile creation page if required fields are missing
except UserProfile.DoesNotExist:
return redirect('create_profile') # Redirect to profile creation page if UserProfile does not exist
else:
messages.error(request, "Invalid credentials")
return redirect("Login")
else:
return render(request, "login.html", {'Login': 'Title'})
def logout(request):
auth.logout(request)
return redirect('/')
def check_user_tag(request):
if request.method == 'GET' and 'tag' in request.GET:
tag = request.GET['tag']
user_exists = User.objects.filter(username=tag).exists()
return JsonResponse({'exists': user_exists})
return JsonResponse({'error': 'Invalid request'})
def profile(request):
return render(request,'profile.html',{'Profile':'Title'})
my models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, default=None)
usertag = models.CharField(max_length = 20, default='@')
matricNumber = models.CharField(max_length=100)
Department = models.CharField(max_length=100)
faculty_choices = [
('Science', 'School of Science'),
('Computing', 'School of Computing'),
('Engineering', 'School of Engineering'),
('Agriculture', 'School of Agriculture'),
('Management', 'School of Management Technology'),
('Health', 'School of Health'),
('Earth', 'School of Earth and Mineral Sciences'),
('Postgraduate', 'School of Postgraduate Studies'),
('Predegree', 'School of Predegree Studies'),
('Environmental', 'School of Environmental Technology'),
]
faculty = models.CharField(max_length=100, choices=faculty_choices)
profile_picture = models.ImageField(upload_to='profiles/', default='static/media/images/avatar.png')
class Posts(models.Model):
authordp = models.ImageField(upload_to='static/media/profiles/', null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.CharField(max_length=200)
image = models.FileField(upload_to='static/media/images/', null=True, blank=True)
def save(self, *args, **kwargs):
self.authordp = self.author.userprofile.profile_picture
super().save(*args, **kwargs)
class Videos(models.Model):
authordp = models.ImageField(upload_to='static/media/profiles/', null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.CharField(max_length=50)
video = models.FileField(upload_to='static/media/videos/', null=True, blank=True, default='static/media/videos/Numbbug.mp4')
def save(self, *args, **kwargs):
self.authordp = self.author.userprofile.profile_picture
super().save(*args, **kwargs)
my forms.py
import re
from django.contrib.auth.models import User
from django import forms
from .models import UserProfile
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password', 'password2']
widgets = {
'username': forms.TextInput(attrs={'class':'shadow', 'required': 'true'}),
'email': forms.TextInput(attrs={'class':'shadow', 'required': 'true'}),
'password': forms.TextInput(attrs={'class':'shadow'}),
'password2': forms.TextInput(attrs={'class':'shadow'}),
}
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get('password')
password2 = cleaned_data.get('password2')
if password and password2 and password != password2:
raise forms.ValidationError("Passwords do not match")
return cleaned_data
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['matricNumber', 'Department', 'faculty', 'profile_picture','usertag']
widgets = {
'matricNumber': forms.TextInput(attrs={'placeholder': 'DEPT/XX/XXXX', 'class': 'shadow ', 'required': 'true'}),
'Department': forms.TextInput(attrs={'class': 'shadow ', 'required': 'true'}),
'faculty': forms.Select(attrs={'class': 'shadow ', 'required': 'true'}),
'profile_picture': forms.FileInput(attrs={'class': 'shadow '}),
'usertag': forms.TextInput(attrs={'type': 'text', 'id': 'id_user_tag', 'name': 'user_tag', 'required': 'true'}),
}
def clean_usertag(self):
usertag = self.cleaned_data['usertag']
if UserProfile.objects.filter(usertag=usertag).exists():
raise forms.ValidationError("This usertag is already in use.")
return usertag
def clean_matricNumber(self):
matricNumber = self.cleaned_data.get('matricNumber')
pattern = re.compile(r'^[a-z,A-Z][a-z,A-Z][a-z,A-Z]/[0-9][0-9]/[0-9][0-9][0-9][0-9]$')
if not pattern.match(matricNumber):
raise forms.ValidationError('Invalid matric number format. Example format: EXX/19/1201')
return matricNumber
my createAccount.html
{% extends "Base.html" %} {% load static %} {% block content %}
<div class="log">
<form method="post">
{% csrf_token %}
<div>
<img src="{% static 'media/images/Futalogo.jpg' %}" />
</div>
<h4>Create Account</h4>
{{ user_form.username.errors }}
<div>
<label for="id_username">Username</label>
{{ user_form.username }}
</div>
{{ user_form.email.errors }}
<div>
<label for="id_email">Email</label>
{{ user_form.email }}
</div>
{{ user_form.password.errors }}
<div>
<label for="id_password">Password</label>
{{ user_form.password }}
</div>
{{ user_form.password2.errors }}
<div>
<label for="id_password">Confrim Password</label>
{{ user_form.password2 }}
</div>
<button class="shadow" id="logbtn" type="submit">Sign Up</button>
</form>
</div>
{% endblock %}
my createProfile.html
{% extends "Base.html" %} {% load static %} {% block content %}
<div>
<div class="log">
<form class="shadow" method="post" enctype="multipart/form-data" action="">
{% csrf_token %}
<h4>Welcome <span class="userWelcome">{{user.username}}</span></h4>
<div>
<img
class="shadow-lg select-pic"
id="profile-pic"
src="{% static 'media/images/upload.png' %}"
alt="Profile Picture"
onclick="uploadImage()" />
<input type="file" id="file-input" style="display: none" />
</div>
{{ form.usertag.errors }}
<!-- Display any form validation errors for department field -->
<div class="input-wrapper">
<label for="id_user_tag">User Tag</label>
<span class="at-symbol">@</span>
{{ form.usertag }}
<span id="tag-status"></span>
</div>
<p class="text-danger">{{ form.matricNumber.errors }}</p>
<div>
<label for="id_matricNumber">Matric Number</label>
{{ form.matricNumber }}
</div>
{{ form.faculty.errors }}
<!-- Display any form validation errors for faculty field -->
<div>
<label for="id_faculty">Faculty</label>
{{ form.faculty }}
</div>
{{ form.Department.errors }}
<!-- Display any form validation errors for department field -->
<div>
<label for="id_department">Department</label>
{{ form.Department }}
</div>
<button id="logbtn" class="shadow" type="submit">Submit</button>
</form>
</div>
</div>
{% endblock %}
my url.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.home ,name='Homepage'),
path('createAccount', views.createAccount, name= 'createAccount'),
path('create_profile', views.createProfile, name= 'createProfile'),
path('login', views.login, name= 'Login'),
path('logout', views.logout, name = 'logout'),
path('profile', views.profile, name= 'profilePage'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I tried creating a user sign up page that will redirect them to user create profile page after a successful sign up but when I click on sign up the page just loads again to sign up page and a user is created but the terminal prints working