2013-04-23 25 views
2

我怎麼可以給一個額外的參數到的ModelForm對象喜歡這裏: initail的的ModelForm對象給一個參數爲對象

form = ChangeProfile(request.POST, initial={'first_name':costumer.first_name, 'last_name':costumer.last_name}, extraParameter) 

,我怎麼能得到extraParameter在這個類:

class ChangeProfile(ModelForm): 

它不是這樣的神的想法來創建這樣

def __init__(self, request, initial, extraParamter): 

什麼個構造器我應該在這裏嗎?

回答

0

對於這種情況,您需要覆蓋__init__

但是您的__init__的簽名有一個錯誤。

你應該這樣做:

class ChangeProfile(ModelForm): 
    def __init__(self, *args, **kwargs): 
     self.extraParameter = kwargs.pop("extraParameter") 
     super(ChangeProfile, self).__init__(*args, **kwargs) 
     #any other thing you want 

從視圖:

extraParameter = "hello" 

#GET request 
form=ChangeProfile(initial={'first_name':costumer.first_name, 'last_name':costumer.last_name}, extraParameter=extraParameter) 

#POST request 
form=ChangeProfile(request.POST ,initial={'first_name':costumer.first_name, 'last_name':costumer.last_name}, extraParameter=extraParameter) 
3

您可以傳遞參數在很多方面,比如一個簡單的Python類,你必須小心,只是爲了不打破的默認行爲的Django Forms/ModelForms。

class YourForm(forms.Form): 
    def __init__(self, custom_arg=None, *args, **kwargs): 
     # We have to pop the 'another_arg' from kwargs, 
     # because the __init__ from 
     # forms.Form, the parent class, 
     # doesn't expect him in his __init__. 
     self.another_arg = kwargs.pop('another_arg', None) 

     # Calling the __init__ from the parent, 
     # to keep the default behaviour 
     super(YourForm, self).__init__(*args, **kwargs) 

     # In that case, just our __init__ expect the custom_arg 
     self.custom_arg = custom_arg 

     print "Another Arg: %s" % self.another_arg 
     print "Custom Arg: %s" % self.custom_arg 


# Initialize a form, without any parameter 
>>> YourForm() 
Another Arg: None 
Custom Arg: None 
<YourForm object at 0x102cc6dd0> 

# Initialize a form, with a expected parameter 
>>> YourForm(custom_arg='Custom arg value') 
Another Arg: None 
Custom Arg: Custom arg value 
<YourForm object at 0x10292fe50> 

# Initialize a form, with a "unexpected" parameter 
>>> YourForm(another_arg='Another arg value') 
Another Arg: Another arg value 
Custom Arg: None 
<YourForm object at 0x102945d90> 

# Initialize a form, with both parameters 
>>> YourForm(another_arg='Another arg value', 
      custom_arg='Custom arg value') 
Another Arg: Another arg value 
Custom Arg: Custom arg value 
<YourForm object at 0x102b18c90> 
相關問題