[Django]-Django v2+ regex for custom path converter to handle csv

4👍

Unless I’m missing something, you don’t need a complicated regular expression. You simply have to capture any string not containing a slash (/), the splitting up is handled by to_python(). You can simply use the regex from the built-in StringConverter:

class CSVConverter:
    regex = '[^/]+'

    def to_python(self, value):
        return value.split(',')

    def to_url(self, value):
        return ','.join(value)

Alternatively, you can also subclass StringConverter:

from django.urls.converters import StringConverter

class CSVConverter(StringConverter):

    def to_python(self, value):
        return value.split(',')

    def to_url(self, value):
        return ','.join(value)

Leave a comment