Matthew Rankin
Matthew Rankin

Reputation: 461217

Periods in Django's SlugField

Question

Code

Here's an excerpt of the model:

class Project(models.Model):
    slug_code = models.SlugField(max_length=15)

Here's the applicable initial_data.yaml excerpt:

- model: myapp.project
  pk: 1
  fields:
    slug_code: TIDE.024

The yaml fixture initial_data.yaml is installed without any errors. When I log into the Admin and look at the Project model, I can see that the SlugField slug_code contains TIDE.024, but when I change the slug_code field to say TIDE.025 the Admin generates the following error:

Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.

Configuration

Upvotes: 0

Views: 824

Answers (2)

Jordan Reiter
Jordan Reiter

Reputation: 21032

You can always add a custom function if you want to forbid illegal characters from your field.

Something like:

def save(self, *args, **kwargs):
    import re
    if re.search(r"[^-\w]",self.slug_field):
        raise Exception("This value can only contain letters, numbers, underscores, and dashes.")
    super(self, Project).save(*args, **kwargs)

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799310

The value in the SlugField is only checked in forms, not in the database.

Upvotes: 4

Related Questions