0

I've established a variable inside my def init function inside my form that I want to be able to access within def clean() in that same form.

def __init__(self, *args, **kwargs):                         
        super(UserOrderForm, self).__init__(*args, **kwargs)
        car = 'BMW'

def clean(self):
       cleaned_data = super(UserOrderForm, self).clean()
       print(car)

When I print car, I'm told that

name 'car' is not defined

Is there a way to do this?

Thanks!

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
Jason Howard
  • 1,464
  • 1
  • 14
  • 43

3 Answers3

2

In Python you declare instance attributes using self, you must change your code to

def __init__(self, *args, **kwargs):                         
        super(UserOrderForm, self).__init__(*args, **kwargs)
        self.car = 'BMW'

def clean(self):
       cleaned_data = super(UserOrderForm, self).clean()
       print(self.car)

In your original code, the variable car does exists only inside the __init__ method.

Primusa
  • 13,136
  • 3
  • 33
  • 53
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
0

i think you make the car a member variables, then set it in the init method with self.car = "bmw".

then when you want to see the value in clean, you call self.clean

python class instance variables and class variables

Julian
  • 550
  • 1
  • 4
  • 16
0

not sure what you're trying to do, but your form should declare a model to get a queryset to work with.

class UserOrderForm(forms.ModelForm):

    class Meta:
        model = Cars
        fields = ['manufacturer', 'model_number', 'etc']
        widgets = {'manufacturer': forms.Select}

Your users will provide the input, for example selecting BMW from a select field.

Check out: https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/

crappy_hacker
  • 191
  • 3
  • 6