Alan Tingey
Alan Tingey

Reputation: 961

Django Form - Passing Values

I have the following form and can't seem to use the "self.currentSelectedTeam1" as the initial value for team1 as can be seen at the bottom. When I do try this I get the following error:

team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam1)
NameError: name 'self' is not defined

Form:

class SelectTwoTeams(BootstrapForm):

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        self.curentSelectedTeam1 = kwargs.pop('curentSelectedTeam1', None)
        self.curentSelectedTeam2 = kwargs.pop('curentSelectedTeam2', None)
        super(SelectTwoTeams, self).__init__(*args, **kwargs)
        queryset = StraightredTeam.objects.filter(currentteam = 1)

        self.fields['team1'].queryset = queryset
        self.fields['team2'].queryset = queryset

    team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam1)
    team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam2)

Many thanks in advance for any help, Alan.

Upvotes: 0

Views: 40

Answers (2)

Soviut
Soviut

Reputation: 91515

This doesn't work becasue the fields team1 and team2 are created before __init__ is called because they're instance members.

This means that self.curentSelectedTeam1 and self.curentSelectedTeam2 aren't available yet and are most likely None.

In order to set initial values on the form, you need to do so when you instantiate the form itself.

team1_pk = 0
team2_pk = 1

form = SelectTwoTeams(initial={'curentSelectedTeam1': team1_pk, 'curentSelectedTeam2': team2_pk})

You'll need to either remove your current __init__ override or call super() to allow the initial values to be passed to the form's default constructor.

Upvotes: 2

Andrii Rusanov
Andrii Rusanov

Reputation: 4606

The problem is in self keyword in team1 and team2 variables. The thing is they are on the class-level, and the self is available on the instance level(inside methods, excluding static methods and class methods)

To make it work you need to do the same with self.fields['team1'].queryset:

self.fields['team1'].initial = self.curentSelectedTeam1

inside __init__ method.

Upvotes: 2

Related Questions