2009-02-17 17 views
29

Django:我怎樣才能把一個<a>超鏈接從一個表單clean()方法的django驗證錯誤?我想提出一個驗證錯誤,並且在錯誤文本中有一個超鏈接,它有一個鏈接可以幫助用戶糾正錯誤。這是我在表單的一個乾淨方法中提出的驗證錯誤。有沒有一種方法可以將該驗證錯誤的HTML標記爲可安全輸出爲HTML?Django:我怎麼能把一個<a>超鏈接從一個表單clean()方法的django驗證錯誤?

回答

37

上的錯誤消息字符串呼叫mark_safe當你提高ValidationError

+0

從` django.utils.safestring import mark_safe` (Django 1.10) – 2016-09-25 21:42:36

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.")}) 
相關問題