3

Note: prior to posting I already searched for csv regex. The best regex I found for csv so far can be found in the answer here.


I would like to create a custom path converter for handling a csv e.g. something like:

register_converter(CSVConverter, 'csv')

urlpatterns = [
    ...
    path('csv/<csv:list_of_values>/', views.csv_view, name='csv_view'),
    ...
]

where each value of list_of_values is a string that does not need to be wrapped in quotes e.g.

http://localhost:8000/csv/value1,value2,value3/

I tried the following:

class CSVConverter:
    # see https://stackoverflow.com/a/48806378/5623899
    regex = "(?:,|\n|^)(\"(?:(?:\"\")*[^\"]*)*\"|[^\",\n]*|(?:\n|$))"

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

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

but this doesn't work...

SumNeuron
  • 4,850
  • 5
  • 39
  • 107

1 Answers1

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)
theY4Kman
  • 5,572
  • 2
  • 32
  • 38
Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75