How do I write a Class-Based Django Validator?

2024/10/5 7:20:28

I'm using Django 1.8.

The documentation on writing validators has an example of a function-based validator. It also says the following on using a class:

You can also use a class with a __call__() method for more complex or configurable validators. RegexValidator, for example, uses this technique. If a class-based validator is used in the validators model field option, you should make sure it is serializable by the migration framework by adding deconstruct() and __eq__() methods.

  • What are the pros/cons of class-based against function-based validators?
  • What is __call__() used for, and how is it used?
  • What is deconstruct() used for, and how is it used?
  • What is __eq__() used for, and how is it used?

An example would be helpful. A full answer may also be worth submitting to be in the official documentation.

Thanks!

Answer

A big advantage of validator functions is that they are really simple. They simply take one value as an argument, check that it's valid, and and raise ValidationError if it's not. You don't need to worry about deconstruct and __eq__ methods to make migrations work.

The validate_even example in the docs is much simpler than a validator class would be.

def validate_even(value):if value % 2 != 0:raise ValidationError('%s is not an even number' % value)

If you need to check divisibility by other numbers as well, then it would be worth creating a validator class ValidateDivisibleBy. Then you could use ValidateDivisibleBy(2), ValidateDivisibleBy(3) and so on. But a lot of the time, a validator function is good enough.

https://en.xdnf.cn/q/70513.html

Related Q&A

python synthesize midi with fluidsynth

I cant import fluidsynth. [Maybe theres an better module?]Im trying to synthesize midi from python or pygame. I can send midi events from pygame. Im using mingus, and it seemed pyfluidsynth would be g…

Convenient way to handle deeply nested dictionary in Python

I have a deeply nested dictionary in python thats taking up a lot of room. Is there a way to abbreviate something like this master_dictionary[sub_categories][sub_cat_name][attributes][attribute_name][s…

Running tests against existing database using pytest-django

Does anybody know how to run Django Tests using pytest-django against an existing (e.g. production) database? I know that in general, this is not what unit tests are supposed to do, but in my case, I…

Python, Timeout of Try, Except Statement after X number of seconds?

Ive been searching on this but cant seem to find an exact answer (most get into more complicated things like multithreading, etc), I just want to do something like a Try, Except statement where if the …

MemoryError while pickling data in python

I am trying to dump a dictionary into pickle format, using dump command provided in python. The file size of the dictionary is around 150 mb, but an exception occurs when only 115 mb of the file is dum…

numpy dimensions

Im a newbie to Numpy and trying to understand the basic question of what is dimension,I tried the following commands and trying to understand why the ndim for last 2 arrays are same?>>> a= ar…

DataFrame Plot: how to sort X axis

I am plotting some counts from a field of dataframe (pandas) and I found that the X axis is sorted by the counts (descending order). Instead is it possible to sort by the alphabetical order of the fiel…

In-place custom object unpacking different behavior with __getitem__ python 3.5 vs python 3.6

a follow-up question on this question: i ran the code below on python 3.5 and python 3.6 - with very different results:class Container:KEYS = (a, b, c)def __init__(self, a=None, b=None, c=None):self.a …

Different ways of using __init__ for PyQt4

So... Im working on trying to move from basic Python to some GUI programming, using PyQt4. Im looking at a couple different books and tutorials, and they each seem to have a slightly different way of k…

Numpy: Reshape array along a specified axis

I have the following array:x = np.arange(24).reshape((2,3,2,2)) array([[[[ 0, 1],[ 2, 3]],[[ 4, 5],[ 6, 7]],[[ 8, 9],[10, 11]]],[[[12, 13],[14, 15]],[[16, 17],[18, 19]],[[20, 21],[22, 23]]]])I wou…