2014-04-25 74 views
5

我想對django-allauth中的字段做一些額外的驗證。例如,我想阻止使用免費的電子郵件地址。所以我想在註冊時運行此方法Django-Allauth中的自定義表單驗證

def clean_email(self): 
    email_domain = self.cleaned_data['email'].split('@')[1] 
    if email_domain in self.bad_domains: 
     raise forms.ValidationError(_("Registration using free email addresses is prohibited. Please supply a different email address.")) 

同樣,我想在除電子郵件地址之外的其他字段上運行自定義驗證。我該如何執行此操作?

回答

4

在allauth配置中有一些適配器。例如下面這個:

ACCOUNT_ADAPTER (="allauth.account.adapter.DefaultAccountAdapter") 
    Specifies the adapter class to use, allowing you to alter certain default behaviour. 

您可以通過覆蓋默認的適配器來指定新的適配器。只需覆蓋clean_email方法。

class MyCoolAdapter(DefaultAccountAdapter): 

    def clean_email(self, email): 
     """ 
     Validates an email value. You can hook into this if you want to 
     (dynamically) restrict what email addresses can be chosen. 
     """ 
     *** here goes your code *** 
     return email 

然後修改ACCOUNT_ADAPTER在settings.py

ACCOUNT_ADAPTER = '**app**.MyCoolAdapter' 

檢查的默認行爲: https://github.com/pennersr/django-allauth/blob/master/allauth/account/adapter.py

+0

要拒絕的電子郵件地址,提高了'django.forms.ValidationError'例外。 – Flimm

+0

在另一個表單域上如何做到這一點? – Hakim