Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

custom validators

Hi,

In the code below, why the method 'must_be_empty' is outside the class. Being outside, it can be called anytime, anywhere?

def must_be_empty(value):
    if value:
        raise forms.ValidationError('is not empty')


class SuggestionForm(forms.Form):
    name = forms.CharField()
    email = forms.EmailField()
    suggestion = forms.CharField(widget=forms.Textarea)
    honeypot = forms.CharField(required=False,
                               widget=forms.HiddenInput,
                               label="Leave empty",
                               validators=[must_be_empty])

Besides, the method takes one argument 'value'. How could it be called by the validator without passing a parameter : 'validators=[must_be_empty]'

Thanks for your help

2 Answers

Here the the "must_be_empty()" function is global (as you said, not in the class) because of the "charfield", which takes in an array (validators) of functions that aren't part of a specific class. From what I understand form this course, the "charfield" element takes the validators array and just uses each item in it as a function with the value argument as the input in this field (in the html form).

thanks for the response