Aleksei Khatkevich
Aleksei Khatkevich

Reputation: 2197

Dynamically add ProhibitNullCharactersValidator into the form's __init__ in Django. Need an advice

Quite a simple question for someone who knows the answer.

Is it possible to dynamically add validator to a form’s field in froms init ???

I want to do something like this:


class SomeForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.pk = kwargs.pop("pk", None)
        forms.ModelForm.__init__(self, *args, **kwargs)

        if self.pk == some integer:
    self.fields[field].validator(s)……..  # and I don’t know what to type here
        else:
    do something else…

Goal is to add ProhibitNullCharactersValidator dynamically depending on the self.pk to self.fields[field] (one field of the form)

Thank you in advance and sorry if this questions is dumb.

Upvotes: 0

Views: 193

Answers (1)

Alasdair
Alasdair

Reputation: 308939

Since you want to add the validator to a particular field you can override the clean_ method for that field, and call the validator there.

class SomeForm(forms.ModelForm):
    def clean_myfield(self):
        value = self.cleaned_data.get('myfield')
        if self.instance.pk == some_value:
            ProhibitNullCharactersValidator(value)
        return value

Upvotes: 1

Related Questions