[Answered ]-How should I add custom validation to the Django admin for a non-standard model field?

1👍

Short Answer: The issue will be fixed in the upcoming release


You must create a few custom classes to get this working,

  • custom widget
  • custom form field
  • custom model field
# widgets.py
from django import forms


class VectorWidget(forms.TextInput):
    def format_value(self, value):
        try:
            value = value.tolist()
        except AttributeError:
            # value could be None
            pass
        return super().format_value(value)
# forms.py
from django import forms


class VectorFormField(forms.CharField):
    widget = VectorWidget
# fields.py
from django.db import models
from pgvector.django import VectorField


class CustomVectorField(_VectorField):
    def validate(self, value, model_instance):
        super().validate(value.tolist(), model_instance)

    def run_validators(self, value):
        super().run_validators(value.tolist())

    def formfield(self, **kwargs):
        return super().formfield(form_class=VectorFormField, **kwargs)
# models.py

class Vector(models.Model):
    test = CustomVectorField(dimensions=3)

    def __str__(self):
        return str(self.test)

References

👤JPG

0👍

When using the built-in validation methods doesn’t work, you can instead add validation in the save method of the model, for example:

models.py

from django.core.exceptions import ValidationError

class MyModel(...):
    array_field = models.ArrayField(...)
    ...

    def save(self, *args, **kwargs):
    
        # raise an error and do not save:
        # check the array, in this example just checking if it is empty:
        if not self.array_field:
            raise ValidationError(
                "the `array_field` cannot be empty",
                ...,
            )

        super().save(*args, **kwargs)
👤Daniel

Leave a comment