[Django]-Django: How can I put an <a> hyperlink in a django validation error from a forms clean() method?

42👍

Call mark_safe on the error message string when you’re raising the ValidationError

13👍

You can do it on the form field definition without needing to raise a form level ValidationError like so:

class RegistrationForm(ModelForm):
    ...

    ### Django established methods
    # form wide cleaning/validation
    def clean_email(self):
        """ prevent users from having same emails """
        email = self.cleaned_data["email"]
        try:
            User.objects.get(email__iexact=email)
            raise forms.ValidationError(
                    mark_safe(('A user with that email already exists, click this <a href="{0}">Password Reset</a> link'
                            ' to recover your account.').format(urlresolvers.reverse('PasswordResetView')))
                            )
        except User.DoesNotExist:
            return email

    ...

    ### Additional fields
    location = forms.RegexField(max_length=255,
        regex=r"^[\w' -]+, [\w'-]+, [\w'-]+, [\w'-]+$", #ex 1 Mclure St, Kingston, Ontario, Canada
        help_text="location, ex: Suite 212 - 1 Main St, Toronto, Ontario, Canada",
        error_messages={
            'invalid': mark_safe("Input format: <strong>suite - street</strong>, <strong>city</strong>, " 
                                "<strong>province/state</strong>, <strong><u>country</u></strong>. Only letters, "
                                "numbers, and '-' allowed.")})

Leave a comment