arne
arne

Reputation: 225

Django function based view get_form_kwargs

I have the following problem.

Normally in Django Class based views the get_form_kwargs method is used to supply the kwargs to the forms __init__(). For example:

class ComponentForm(forms.ModelForm):
    diameter = forms.ModelChoiceField(queryset=Diameter.objects.all(), label='Diameter') # required=True, 

    class Meta:
        model = Component
        fields = [
            'component_type',
            'diameter',
            'length'
        ]

    def __init__(self, *args, **kwargs):
        circuit = kwargs.pop('circuit')
        project = kwargs.pop('project')
        super(ComponentForm, self).__init__(*args, **kwargs)
        self.fields['diameter'].queryset = Diameter.objects.filter(project=project, material = circuit.material_type)

In the example code above, the "circuit" and "project" are supplied by the get_form_kwargs method in the corresponding view.

The question is now how to pass these kwargs to the ComponentForm __init__() using a function based view?

Upvotes: 1

Views: 2055

Answers (2)

wobbily_col
wobbily_col

Reputation: 11921

Two ways.

Specify the directly in the constructor call.

form = ComponentForm(keyword_arg1=value1, keyword_args2=value2)

Alternatively build up a dictionary and pass it in with **kwargs syntax - I find this useful when dynamically adding attributes, and also when using inheritance (like the call to super().init() in your example).

kwargs = {keyword_arg1: value1}
kwargs.update({keyword_arg2:value2}) # usually with conditionals to specify what gets added
form = ComponentForm(**kwargs)

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599876

Well, you just pass them.

form = ComponentForm(circuit=whatever, project=whatever)

Upvotes: 0

Related Questions