Mike
Mike

Reputation: 190

Overridden clean function not being called

The documentation says (which I have done)

The clean_() method is called on a form subclass – where is replaced with the name of the form field attribute.

Next it is telling me that I should do (I believe I have done so)

You will need to look up the value of the field in self.cleaned_data

My Form

class CreatePostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = (
            'title', 'text', 
        )

        def clean_text(self):
            data = self.cleaned_data['text']
            print(data)

            #check if word count is <30
            if len(data.split()) < 30:
                raise forms.ValidationError(('Please write at least 30 words,\
                                    %(count)s words is not long enough'), params={'count':count})
            return data

My View

@login_required
def create_new_post(request):
    if request.method == 'POST':
        form = CreatePostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.created = timezone.now()
            post.save()
            return redirect('post-detail', pk=post.pk)
    else:
        form = CreatePostForm()
    return render(request, 'journal/create_post.html', {'form':form})

So I tried printing to see if the function is even being called, but nothing was being printed in the console.

Can anyone explain what I am doing wrong? Why is this happening?

Upvotes: 0

Views: 53

Answers (1)

Alasdair
Alasdair

Reputation: 309049

Your indentation is incorrect. At the moment, clean_text is a method of the Meta class.

class CreatePostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = (
            'title', 'text', 
        )

        def clean_text(self):
            ...

It should be indented at the same level as the Meta class:

class CreatePostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = (
            'title', 'text', 
        )

    def clean_text(self):
        ...

Upvotes: 3

Related Questions