2

如何为 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):

我应该在这里做什么?

4

2 回答 2

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>
于 2013-04-23T06:10:33.960 回答
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)
于 2013-04-23T06:10:06.960 回答