Menachem Hornbacher
Menachem Hornbacher

Reputation: 2166

Django validate unique charfield in admin console

I have 2 models with a CharField called path. On one of them I need to force it to end with / and on the other one anything but /. Also this field has to be unique and indexed. Here is the solution I came up with so far:

Dir model (must end in '/')

#   The path for sorting, e.g. /stuff/00-1/. Must be unique and is indexed for performance.
path = models.CharField(max_length=75, unique=True, db_index=True, blank=False, validators=RegexValidator(regex=r'^/[A-Za-z0-9/-_]+/$', message="Please enter a valid Dir Path")) 
...   
def save(self, *args, **kwargs):
    #   If the path does not end in "/" add it.
    if not self.path.endswith("/"):
        self.path += "/"
    if not self.path.startswith("/"):
        self.path = "/" + self.path
    #  print the result
    print("Saving path {}".format(self.path))
    super(Dir, self).save(*args, **kwargs)  # Call the "real" save() method.

I have attempted a try except around the call to super() however that changes nothing. How to I tell the admin console to validate the data so I get a not unique error before it saves and crashes so the admin can change it?

TL;DR how do I get the red line to appear above a charfeild in the admin console if it fails custom regex validation?

Upvotes: 0

Views: 572

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

For custom validation in admin, you need a custom form for it in order to code your specific logic. save() method in django is never a good place to do validation because it doesn't return anything to the user form. Check django doc on how to have your own form for django admin. Check also how to validate a django form.

Upvotes: 1

Related Questions