为对象提供参数

时间:2013-04-23 05:36:02

标签: python django

如何向ModelForm对象提供额外的参数,如下所示: 启动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):

我该怎么办?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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)