Django:如何从表单clean()方法中将django验证错误中的超链接放入?我想提出验证错误,并在错误文本中有一个
超链接,其中包含一个链接,可以帮助用户更正错误.这是我在表单的干净方法中提出的验证错误.有没有办法将该验证错误的HTML标记为可以安全地输出为HTML?
mark_safe
当你举起时,请调用错误消息字符串ValidationError
您可以在表单字段定义上执行此操作,而无需像这样提出表单级别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 Password Reset 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: suite - street, city, " "province/state, country. Only letters, " "numbers, and '-' allowed.")})