I am trying to build a registration form for a user on a webpage using python and the Django framework. The form works fine and registers a user if all the fields are valid and Django has built in error messages if fields are left blank etc which work fine. However, I am trying to add my own error for if the 'password' and 'confirm password' fields don't match. If they don't match I get an error stating: 'The view main.views.register didn't return an HttpResponse object. It returned None instead.' My question is how would I successfully return the registration page with the error displayed to the user?
Here is my views.py code:
def register(request):
if request.method == "GET":
register_form = RegisterForm()
return render(request, "main/register.html", {
'form': register_form
})
else:
register_form = RegisterForm(request.POST)
if register_form.is_valid():
register_form.save()
return render(request, "main/login.html")
and here is my forms.py code:
class RegisterForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
confirm_password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'password']
def clean(self):
cleaned_data = super(RegisterForm, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
self.add_error("confirm_password", "Password does not match")
What I have tried:
I have tried rendering the register webpage after submission, but I can't work out how to render it with my added errors