2012-02-24 60 views
0

功能我有以下的基類(代碼縮短):重寫在python

class SignupForm(GroupForm): 

    username = forms.CharField(
     label = _("Username"), 
     max_length = 30, 
     widget = forms.TextInput() 
    ) 

    def __init__(self, *args, **kwargs): 
     super(SignupForm, self).__init__(*args, **kwargs) 
     if REQUIRED_EMAIL or EMAIL_VERIFICATION or EMAIL_AUTHENTICATION: 
      self.fields["email"].label = ugettext("Email") 
      self.fields["email"].required = True 
     else: 
      self.fields["email"].label = ugettext("Email (optional)") 
      self.fields["email"].required = False 


    def after_signup(self, user, **kwargs): 
     """ 
     An extension point for subclasses. 
     """ 
     pass 

我想要做的是覆蓋after_signup()功能和username場像這樣:

class CompanySignupForm(SignupForm): 
    #TODO: override fields for company signup form 

    username = forms.CharField(
     label = _("Username TEST"), 
     max_length = 30, 
     widget = forms.TextInput() 
    ) 

    def after_signup(self, user, **kwargs): 
     """ 
     An extension point for subclasses. 
     """ 
     print str('after_signup is has been overwritten') 

我問題: 只有用戶名字段顯示所需的行爲。 after_signup()函數永遠不會被調用。而是調用基類SignupFormafter_signup()函數。我錯了什麼?

編輯:

the imports: 
from django import forms 
from django.contrib.auth.models import User 
from django.utils.translation import ugettext_lazy as _, ugettext 

實例CompanySignupForm:

url(r"^signup/$", CompanySignupForm.as_view(), name="acct_signup") 

after_signup()從在基類的函數beeing稱爲:

def save(self, request=None): 
    # more code here 
    # ... 
    self.after_signup(new_user) 
+1

你能告訴我們你是如何實例化'CompanySignupForm'和調用'after_signup ()'? – NPE 2012-02-24 18:58:57

+0

請顯示您的進口。 – Daenyth 2012-02-24 19:12:01

+0

進口很好,我沒有錯誤。但在這裏他們是:從django導入表格 從django.contrib.auth.models導入用戶 從django.utils.translation導入ugettext_lazy作爲_,ugettext – j7nn7k 2012-02-24 19:19:57

回答

0

使用isinstance()檢查一個實例的類型爲d .__class__以確保您正在實例化CompanySignupForm

另外,您可能還想在CompanySignupForm上創建__init__方法,以確保它不僅僅是實例化超類。

注意:更仔細地閱讀你的編輯你不直接調用after_signup基類功能保存是正確的?如果它存在,這將會調用它的本地方法after_signup。我會拿這個函數出來的基類,並迫使它調用繼承的功能

要檢查版本運行:

signup = CompanySignupForm.as_view() 
print signup.__class__ 

url(r"^signup/$", signup, name="acct_signup") 
+0

你能告訴我一個使用我的代碼的具體例子嗎? – j7nn7k 2012-02-24 20:09:46

+0

添加代碼來檢查類,你可以包括GroupForm代碼,或者as_view()和save()這些代碼調用GroupForm after_signup()函數,我認爲它們是基級函數。 – 2012-02-24 20:14:21

+0

也請投票,如果這有幫助嗎? – 2012-02-24 20:14:40