2013-07-26 23 views
2

我有一個簡單的captcha python/django應用程序。 按照某種算法出現簡單的驗證碼。DRY向上類似的表格類

有兩個幾乎相同的構造函數。不同之處在於繼承。 如何避免代碼重複?

class PostCaptchaForm(PostForm): 
    captcha = CaptchaField() 

    def __init__(self, *args, **kwargs): 
     self.request = kwargs['request'] 
     del kwargs['request'] 

     super(PostCaptchaForm, self).__init__(*args, **kwargs) 

    def clean(self): 
     cleaned_data = super(PostCaptchaForm, self).clean() 

     success = self.is_valid() 
     utils.update_captcha_access(self.request, success) 

     if success: 
      return cleaned_data 
     else: 
      raise forms.ValidationError("captcha validation failed") 


class ThreadCaptchaForm(ThreadForm): 
    captcha = CaptchaField() 

    def __init__(self, *args, **kwargs): 
     self.request = kwargs.pop('request') 

     super(ThreadCaptchaForm, self).__init__(*args, **kwargs) 

    def clean(self): 
     cleaned_data = super(ThreadCaptchaForm, self).clean() 

     success = self.is_valid() 
     utils.update_captcha_access(self.request, success) 

     if success: 
      return cleaned_data 
     else: 
      raise forms.ValidationError("captcha validation failed") 
+0

這是好的,我would'nt擔心改變什麼 –

回答

3

我與多重繼承做到這一點,用鹼驗證碼形式作爲一個mixin,並肩ThreadForm使用或PostForm

class CaptchaFormBase(forms.Form): # or forms.ModelForm, if appropriate 

    captcha = CaptchaField() 

    def __init__(self, *args, **kwargs): 
     self.request = kwargs.pop('request') 
     # this is the same as assigning to self request then deleting the key 

     super(CaptchaFormBase, self).__init__(*args, **kwargs) 


    def clean(self): 
     cleaned_data = super(CaptchaFormBase, self).clean() 

     success = self.is_valid() 
     utils.update_captcha_access(self.request, success) 

     if not success: 
      # this will put things in non_field_errors, you may want to put it in self.errors['captcha'] 
      raise forms.ValidationError("Captcha validation failed") 

     # always make it easy to see that you're returning cleaned_data 
     return self.cleaned_data 


class PostCaptchaForm(PostForm, CaptchaFormBase): 
    pass 


class ThreadCaptchaForm(ThreadForm, CaptchaFormBase): 
    pass 
+0

非常感謝! 它很好用。 –