Форма Django не отправляется на сервер
Когда я создаю новую учетную запись пользователя. Я установил терминал на печать, если форма создания учетной записи работает, и терминал делает это
но созданный аккаунт не отображается на панели администратора django, что означает, что аккаунт не был создан, а поскольку аккаунт не был создан, я не получаю перенаправление на страницу создания профиля
my views.py
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)
Я попытался создать страницу регистрации пользователя, которая будет перенаправлять их на страницу создания профиля пользователя после успешной регистрации, но когда я нажимаю на кнопку регистрации, страница просто загружается снова на страницу регистрации и пользователь создается, но терминал печатает работает