My login and register page doesnt work when i click the button and my url config is good
i am building a django project and i keep getting this error:- django.db.utils.IntegrityError: null value in column "id" of relation "validation" violates not-null constraint DETAIL: Failing row contains (null, 7, 839510, 0, 2024-10-29 19:51:34.057435+00, f, null). I think it is something to do with my datbase,i use pgadmin
views.py
from django.shortcuts import redirect, render
from django.contrib.auth import login, authenticate
from django.core.mail import send_mail
from django.utils import timezone
from .forms import UserRegistrationForm, UserLoginForm, VerificationForm
from .models import Validation
# User Registration View
def register_view(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
token = random.randint(100000, 999999)
Validation.objects.create(user=user, token=token,
expired=timezone.now() + timezone.timedelta(hours=1))
send_mail(
'Your Verification Code',
f'Use this code to verify your account: {token}',
settings.DEFAULT_FROM_EMAIL,
[user.email],
)
return redirect('verification')
else:
form = UserRegistrationForm()
return render(request, 'registration/register.html', {'form': form})
# Verification View
def verify_view(request):
if request.method == 'POST':
form = VerificationForm(request.POST)
if form.is_valid():
token = form.cleaned_data['token']
try:
validation = Validation.objects.get(user=request.user)
if validation.token == int(token) and validation.expired >= timezone.now():
validation.validation_status = True
validation.save()
return redirect('profile')
else:
# Handle case where verification fails
except Validation.DoesNotExist:
pass
else:
form = VerificationForm()
return render(request, 'registration/verify_email.html', {'form': form})models.py
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
status = models.CharField(max_length=50, null=True, blank=True)
company_name = models.TextField(null=True, blank=True)
logo = models.ImageField(upload_to='logos/', null=True, blank=True)
validation = models.BooleanField(null=True, blank=True)
def __str__(self):
return self.user.username
class Validation(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # Links to User model
token = models.BigIntegerField()
tries = models.IntegerField(default=0)
expired = models.DateTimeField(default=timezone.now) # Set default to current time
validation_status = models.BooleanField(default=False)
validation_date = models.DateTimeField(null=True, blank=True)
def save(self, *args, **kwargs):
if not self.id:
self.expired = timezone.now() + timedelta(minutes=10)
super().save(*args, **kwargs)
def check_expiry_and_increment_tries(self):
if timezone.now() > self.expired:
self.tries += 1
self.expired = timezone.now() + timedelta(minutes=10) # Reset expiry time
self.save()
def generate_verification_code(self):
self.token = uuid.uuid4().int >> 64 # Generate a large integer token
self.expired = timezone.now() + timedelta(minutes=10)
self.save()
def is_verification_code_valid(self):
return timezone.now() <= self.expired
class Meta:
db_table = 'validation'
class Link(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.TextField()
url = models.TextField()
logo = models.TextField(null=True, blank=True)
clicks = models.BigIntegerField(default=0)
def save(self, *args, **kwargs):
is_new = not self.pk
old_logo = None
if self.pk:
old_logo = Link.objects.filter(pk=self.pk).first().logo
super().save(*args, **kwargs)
# Handle logo file saving and old file deletion
if self.logo and is_new:
file_extension = os.path.splitext(self.logo)[1]
new_filename = f"{self.user.username}_{self.id}_{slugify(self.title)}{file_extension}"
user_folder = os.path.join('logos/', self.user.username)
new_path = os.path.join(user_folder, new_filename)
if not os.path.exists(user_folder):
os.makedirs(user_folder)
# Save new logo path to the database
self.logo = new_path
super().save(update_fields=['logo'])
# Delete old logo if replaced
if old_logo and old_logo != self.logo:
try:
old_file_path = os.path.join(settings.MEDIA_ROOT, old_logo)
if os.path.exists(old_file_path):
os.remove(old_file_path)
except Exception as e:
print(f"Error deleting old file: {e}")
class Meta:
db_table = 'links'
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.core.exceptions import ValidationError
from .models import Validation
# User Login Form
class UserLoginForm(AuthenticationForm):
username = forms.CharField(max_length=254, required=True)
password = forms.CharField(label="Password", strip=False, widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password']
# Verification Form
class VerificationForm(forms.Form):
token = forms.CharField(max_length=6, required=True, label="Verification Code")
def clean_token(self):
token = self.cleaned_data['token']
if not token.isdigit() or len(token) != 6:
raise ValidationError("Invalid verification code format.")
return token
# User Registration Form
class UserRegistrationForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=True)
last_name = forms.CharField(max_length=30, required=True)
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']
def clean_email(self):
email = self.cleaned_data['email'].lower()
if User.objects.filter(email=email).exists():
raise ValidationError("A user with that email already exists.")
return email
You don't need to use this line in your Validation and Link models:
id = models.BigAutoField(primary_key=True)
remove this line !
If you want to keep the line:
id = models.BigAutoField(primary_key=True)
You should had auto_created = True :
id = models.BigAutoField(primary_key=True, auto_created = True)
Else it is null as you get in your error message.
But you needn't really this line. Django do it by itself.