Django:我怎样才能放<a> hyperlink in a django validation error from a forms clean() method?</a>

时间:2009-02-17 15:06:17

标签: django django-forms

Django:如何在表单clean()方法的django验证错误中放置<a>超链接?我想提出一个验证错误,并在错误文本中有一个<a href=""></a>超链接,其中有一个链接可以帮助用户纠正错误。这是我在表单的干净方法中提出的验证错误。有没有办法将该验证错误的HTML标记为可安全输出为HTML?

2 个答案:

答案 0 :(得分:41)

在您提出ValidationError

时,请在错误消息字符串上调用mark_safe

答案 1 :(得分:10)

您可以在表单字段定义上执行此操作,而无需像以下那样引发表单级别ValidationError:

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.")})