Issue with Django User Registration: "An error occurred. Please try again."
I am trying to implement user registration and login in my Django project using AJAX. However, even when I enter all the information correctly, I keep getting the error message: "An error occurred. Please try again."
What I have tried: Checked the form validation in forms.py, and it seems to work fine.
Printed register_form.errors in views.py, but it does not show any issues.
Looked at the AJAX response in the browser console, but it always returns the error message without specifying what went wrong.
Tried wrapping the .save() method in a try-except block, but it does not catch any specific exceptions.
Relevant Code views.py:
def login_and_register(request):
login_form = LoginForm()
register_form = CustomUserRegistrationForm()
schools = School.objects.all()
graduation_years = GraduationYear.objects.all()
if request.method == 'POST':
if 'register_submit' in request.POST:
register_form = CustomUserRegistrationForm(request.POST)
if register_form.is_valid():
try:
user = register_form.save()
login(request, user)
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
return JsonResponse({
'success': True,
'redirect_url': reverse('school_login'),
'message': "Registration successful! Please add your school information."
})
messages.success(request, "Registration successful! Please add your school information.")
return redirect('school_login')
except Exception as e:
print(f"Registration error: {str(e)}")
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
return JsonResponse({
'success': False,
'errors': [f"An error occurred during registration: {str(e)}"]
}, status=400)
messages.error(request, f"An error occurred during registration: {str(e)}")
else:
print("Form invalid:", register_form.errors)
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
return JsonResponse({
'success': False,
'errors': register_form.errors
}, status=400)
for field, errors in register_form.errors.items():
for error in errors:
messages.error(request, f"{field}: {error}")
context = {
'login_form': login_form,
'register_form': register_form,
'schools': schools,
'graduation_years': graduation_years,
}
return render(request, 'users/login_register.html', context)
forms.py:
class CustomUserRegistrationForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=True, label="First Name")
last_name = forms.CharField(max_length=30, required=True, label="Last Name")
school = forms.ModelChoiceField(queryset=School.objects.all(), required=True, label="School")
graduation_year = forms.ModelChoiceField(queryset=GraduationYear.objects.all(), required=True, label="Graduation Year")
class Meta:
model = CustomUser
fields = ('first_name', 'last_name', 'school', 'graduation_year', 'password1', 'password2')
def clean(self):
cleaned_data = super().clean()
first_name = cleaned_data.get('first_name', '').strip().lower()
last_name = cleaned_data.get('last_name', '').strip().lower()
if not first_name or not last_name:
raise forms.ValidationError("First Name and Last Name cannot be empty.")
username = f"{first_name}.{last_name}"
counter = 1
temp_username = username
while CustomUser.objects.filter(username=temp_username).exists():
temp_username = f"{username}{counter}"
counter += 1
cleaned_data['generated_username'] = temp_username
return cleaned_data
def save(self, commit=True):
user = super().save(commit=False)
user.username = self.cleaned_data.get("generated_username")
if commit:
try:
user.save()
except Exception as e:
raise forms.ValidationError(f"Error saving user: {e}")
return user
AJAX Code in login.html
fetch(this.action, {
method: 'POST',
body: formData,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
'Accept': 'application/json'
},
credentials: 'same-origin'
})
.then(async response => {
if (response.redirected) {
window.location.href = response.url;
return;
}
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text();
console.error('Unexpected response:', text.substring(0, 100));
throw new Error('Server error: Please try again.');
}
return response.json();
})
.then(data => {
if (data.success) {
if (data.redirect_url) {
window.location.href = data.redirect_url;
} else {
showMessage('Registration successful! Redirecting...', 'success', 'registerMessages');
setTimeout(() => window.location.reload(), 1500);
}
} else if (data.errors) {
Object.entries(data.errors).forEach(([field, errors]) => {
errors.forEach(error => showMessage(`${field}: ${error}`, 'error', 'registerMessages'));
});
} else {
throw new Error('Invalid server response');
}
})
.catch(error => {
console.error('Registration error:', error);
showMessage('An error occurred. Please try again.', 'error', 'registerMessages');
});
What could be the issue? I don’t see any validation errors in register_form.errors.
The .save() method runs inside a try-except block, but it doesn’t catch any specific exceptions.
The AJAX response doesn't provide any meaningful error messages.
Any ideas on what could be causing this issue and how I can debug it further? Thanks in advance!