Surya Banerjee
Surya Banerjee

Reputation: 11

Define class variables with respect to 'self'

So I am trying to set up a django form and I want to use Django Choicefield. Now for choicefield you have to supply it choices which is essentially a list of tuples.

I am trying to use a self.locales_allowed declared in init() in place of the class variable locales_allowed.

class XXX(forms.Form):
    def init(self):
        self.locales allowed = XX




locale = forms.ChoiceField(
    label=label["locale"], choices=locales_allowed, required=True)
#How to use self.locales_allowed here?

I keep getting NameError: name 'self' is not defined if I try to do that. I am looking for a way to get this done.

Upvotes: 0

Views: 78

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

The direct answer is "you can't". But there's no need to use an instance variable for the choices here, just use a class variable instead, which has no concept of self:

class MyForm(forms.Form):
    LOCALES_ALLOWED = ...

    locale = forms.ChoiceField(
        label=label["locale"], choices=LOCALES_ALLOWED, required=True)

I've uppercased LOCALES_ALLOWED because this is a convention in Python for constants, but it's not actually necessary. The key thing here is that you don't need an instance variable, because the choices will be the same for each instance you make.

Upvotes: 2

Related Questions