ValidationError errors in the template page rather than in console

I want to do custom validation for the signup form and show the error in the template page.

class SignUp(generic.CreateView):
    form_class = UserCreationForm   
    success_url = reverse_lazy('dashboard')
    template_name = 'registration/signup.html'

    def form_valid(self, form):
        username, password, email = form.cleaned_data.get('username'), form.cleaned_data.get('password1'), form.cleaned_data.get('email')

        if username == "terms" or username == "privacy":
            raise ValidationError(_('%(username)s is a reserved keyword'), code='reserved', params={'username': username},)

        view = super(SignUp, self).form_valid(form)
        user = authenticate(username=username, password=password, email=email)
        login(self.request, user)
        return view

raise ValidationError is throwing a Django error in console and page. How do I convert this automatically to an error message in the HTML template ?

I solved this in

class UserCreationForm(UserCreationForm):
    def clean_username(self):
        username = self.cleaned_data['username']
        if username == "terms" or username == "privacy":
            raise forms.ValidationError(_('%(username)s is a reserved keyword'), code='reserved', params={'username': username},)
        return username

Awesome! And thanks for sharing the solution. I know others will appreciate it :smiley: xkcd: Wisdom of the Ancients

1 Like