Tristan Tran
Tristan Tran

Reputation: 1513

Add additional initializing arguments for forms.Form __init__

I am creating a form and want to add a dynamic argument as following:

from django import forms

def get_quantity_choices(avail_qty):
    return  [(i, str(i)) for i in range(1, avail_qty)]

class QuantityForm(forms.Form):
    
    def __init__(self, request, avail_qty, *args, **kwargs):
        self.avail_qty_choices = get_quantity_choices(avail_qty)
        
    quantity = forms.TypedChoiceField(
                                choices=avail_qty_choices,
                                coerce=int)

so that I could do this

form = QuantityForm(request.POST, available_quantity)

where available_quantity is a variable dynamically generated elsewhere in my app.

But I keep getting this error message "Undefined name avail_qty_choices" .

What am I doing wrong?

Upvotes: 1

Views: 419

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

That's not how the choices work. The class attributes are intialized when the class is interpreted, when you start the server. The fact that it appears under the __init__ method is not relevant.

You can let the super constructor do the work, and then alter the choices of the quantity field. Initially you can set the choices for example to an empty list:

from django import forms

class QuantityForm(forms.Form):

    quantity = forms.TypedChoiceField(choices=[], coerce=int)
    
    def __init__(self, *args, avail_qty=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['quantity'].choices = get_quantity_choices(avail_qty)

Upvotes: 1

Related Questions