Question:
How can I enable characters other than letters, numbers, underscores, or hyphens in a Django SlugField?

Problem

Wikipedia slugs sometimes contain characters other than letters, numbers, underscores, or hyphens such as apostrophes or commas. For example >Martha's_Vineyard


In my Django app, I am storing Wikipedia slugs in my model which have been pre-populated from a Wikipedia extract. I use the Wikipedia slug to generate slugs for my Django app's own web pages. I'd therefore like to use SlugField as the field type and have a model field definition of:-


slug = models.SlugField(default=None,null=True,blank=True,max_length=255,unique=True)


However as you would expect from the Django documentation this throws an error of 'Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.' when there is an apostrophe or comma in the Wikipedia slug.

Adding allow_unicode=True did not seem to solve the issue:-


slug = models.SlugField(default=None,null=True,blank=True,max_length=255,unique=True,allow_unicode=True,)


ChatGPT suggested a custom slug validator as follows but the same error occurred and ChatGPT concluded 'It appears that Django's SlugField is stricter in its validation than I initially thought, and it may not accept commas (,) even with a custom validator':-


custom_slug_validator = RegexValidator(

    regex=r'^[a-zA-Z0-9'_-]+$',

    message="Enter a valid slug consisting of letters, numbers, commas, underscores, or hyphens.",

    code='invalid_slug'

)


class Route(models.Model):

    slug = models.SlugField(

        default=None,

        allow_unicode=True,

        null=True,

        max_length=255,

        validators=[custom_slug_validator],  # Apply the custom slug validator

        help_text="Enter the Wikipedia slug with special characters (' - or _)",

    )


For now I have reverted to using CharField but suspect I am missing out on some benefits of SlugField. For example, I sometimes generate and store my own slugs in the field where no equivalent page exists in Wikipedia so the standard validation of SlugField has benefits. Can SlugField be customized to accept Wikipedia-valid slugs?


Solution

That's because these are not slugs. Limits the character space, this also ensures that if a person saves the file, the slug can act as a filename on (almost) any system. By adding all sorts of characters, that is no longer guaranteed.


But a SlugField is not very special, it is just a CharField with some "extras". We can see that in the >source code [GitHub]:


def __init__(

    self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs

):

    self.allow_unicode = allow_unicode

    if self.allow_unicode:

        self.default_validators = [validators.validate_unicode_slug]

    super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs)


It thus sets the max_length=50 by default to 50 adds a db_index=True, and adds some validation and a custom form field. The max length is necessary since a lot of databases only index short strings, not long ones.


We thus can make our own custom field, or just work with a CharField:


class Route(models.Model):

    slug = models.CharField(

        default=None,

        db_index=True,

        null=True,

        max_length=50,

        validators=[custom_slug_validator],  # Apply the custom slug validator

        help_text="Enter the Wikipedia slug with special characters (' - or _)",

    )


you can also construct your own custom field, just like they did in Django to automatically set certain values, but a SlugField is thus, behind the curtains, just a CharField with some default values and validators.


Answered by: >Willem Van Onsem

Credit: >StackOverflow


Blog Links

>How to manage the Text in the container in Django?

>Fix webapp stops working issue in Django- Python webapp

>Creating a form in Django to upload a picture from the website

>Sending Audio file from Django to Vue

>How to keep all query parameters intact when changing page in Django?

>Solved: TaskList View in Django

>Implement nested serializers in the Django rest framework

>How to filter events by month in Django?

>Sorting the restframework in Django

>Ways to access instances of models in view in order to save both forms at once in Django

>What makes index.html have such kind of name in Django?

>Fix Module Not Found during Deployment- Django

>Creating a Django with existing directories, files, etc.?

>How to Read a CSV file with PHP using cURL?


Nisha Patel

Nisha Patel

Submit
0 Answers