I have this view for user registration. If the method is GET, just render the form.
If the method is POST, create a form with POST data and try to validate it. Show validation errors if the fields are invalid.
If the form is valid, check if user with the email is already registered. If not, create a new user and login. Otherwise show an error in the page.
# 4 Authentication & authorization
def register(request: HttpRequest):
if request.method == "POST":
form = RegisterForm(request.POST)
# 2 Input validation & sanitization
if form.is_valid():
if not user_repo.is_registered(form.cleaned_data["email"]):
user = user_repo.create(form.cleaned_data)
login(request, user)
# 5 Security logging
logger.info("User registered successfully.")
return redirect("listing-list")
messages.error("Korisnik sa ovom imejl adresom već postoji. Pokušaj ponovo.")
# 5 Security logging
logger.error("Registration failed because an user with the email address already exists.")
return render(request, "auth/register.html", {"form": form})
# 5 Security logging
logger.error("Registration failed due to validation errors.")
return render(request, "auth/register.html", {"form": form})
else:
form = RegisterForm()
# 5 Security logging
logger.info("User 'guest' accessed: Register page.")
return render(request, "auth/register.html", {"form": form})
For some unknown reason, I get error on form.is_valid() saying that a NoneType object is not callable, but the form is not None. The form has custom function-based validators named alpha and adult.
class RegisterForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ["email", "password1", "password2", "phone", "first_name", "last_name", "birth_date"]
# 2 Input validation & sanitization
error_messages = {
"email": {"required": _("email.required")},
"phone": {"required": _("phone.required")},
"first_name": {"required": _("first_name.required")},
"last_name": {"required": _("last_name.required")},
"birth_date": {"required": _("birth_date.required")},
}
widgets = {"birth_date": forms.DateInput(attrs={"type": "date"})}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 3 Input validation & sanitization
self.fields["password1"].error_messages = {"required": _("password1.required")}
self.fields["password2"].error_messages = {"required": _("password2.required")}
self.fields["email"].validators = [EmailValidator(message=_("email.email"))]
self.fields["phone"].validators = [RegexValidator(regex="^\+381 \d{2} \d{6,7}$", message=_("phone.regex"))]
self.fields["first_name"].validators = [alpha(value=self.data.get("first_name"), field="first_name")]
self.fields["last_name"].validators = [alpha(value=self.data.get("last_name"), field="last_name")]
self.fields["birth_date"].validators = [adult]
for field in self.fields:
self.fields[field].widget.attrs["class"] = "form-control"
# 2 Input validation & sanitization
def clean_password2(self):
pass1 = self.cleaned_data["password1"]
pass2 = self.cleaned_data["password2"]
if pass1 and pass2 and pass1 != pass2:
raise forms.ValidationError(_("passowrd2.confirmed"))
return pass2
How can I fix this error?
EDIT: Added the complete view. The form is already complete, unless you expect the custom validators too.