Atma
Atma

Reputation: 29767

django custom form is invalid due to form init

I have the following form:

class PlayerAchievementForm(forms.ModelForm):

    class Meta:
        model = PlayerAchievement
        fields = ('achievement',)

    def __init__(self, *args, **kwargs):
        super(PlayerAchievementForm, self).__init__(**kwargs)
        self.fields['achievement'].queryset = Achievement.objects.filter(input_type=0)

I have the following implementation in a view:

def points(request, action, target=None):

    if request.method == 'POST':
        if target == 'player':
            form = PlayerAchievementForm(request.POST)
            print form.errors
            if form.is_valid():
                print 'valid'
            elif:
                print 'invalid'

On submit, this prints invalid.

If I take out this line in the form:

def __init__(self, *args, **kwargs):
            super(PlayerAchievementForm, self).__init__(**kwargs)
            self.fields['achievement'].queryset = Achievement.objects.filter(input_type=0)

Then it saves without issue. What is wrong with the init?

Upvotes: 0

Views: 133

Answers (2)

koxta
koxta

Reputation: 916

I had the same problem and after a lot of tries, the code that work for me is something like that:

(Notice the first instantiation of the the field at class level.)

class PlayerAchievementForm(forms.ModelForm):

    achievement = Achievement.objects.filter(input_type=0)

    class Meta:
        model = PlayerAchievement
        fields = ('achievement',)

    def __init__(self, *args, **kwargs):
        super(PlayerAchievementForm, self).__init__(**kwargs)
        self.fields['achievement'].queryset = Achievement.objects.filter(input_type=0)

Upvotes: 0

Atma
Atma

Reputation: 29767

I found the answer here: DJango form with custom __init__ not validating

I was missing:

super(PlayerAchievementForm, self).__init__(*args, **kwargs)

Upvotes: 1

Related Questions