hln
hln

Reputation: 1106

Give a parameter to an object

How can I give an extra parameter to a ModelForm object like here: initail the ModelForm object

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

and how can i get the extraParameter in this class:

class ChangeProfile(ModelForm):

it is not such god idea to create a contructor like this

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

what should i do here?

Upvotes: 2

Views: 76

Answers (2)

Luan Fonseca
Luan Fonseca

Reputation: 1517

You can pass parameters in many ways, like a simple Python Class, you must be careful just for not breaking the default behaviour of the 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>

Upvotes: 3

Akshar Raaj
Akshar Raaj

Reputation: 15211

For such scenario, you need to override __init__.

However the signature of your __init__ has a bug.

You should do:

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

From view:

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)

Upvotes: 0

Related Questions