Search code examples
pythonregexdjangodjango-rest-frameworkdjango-rest-viewsets

viewsets not working with ^ and $ added and invalid literal for int() with base 10: on string regex django rest framework


I have the following urls which are directed towards viewsets in djangorestframework

router.register(r'city-list', CityListViewSet, base_name='city-list')

as is above this url works but if I do this:

router.register(r'^city-list$', CityListViewSet, base_name='city-list')

it breaks and I get a 404 error. the ^ is a regex expression for pattern matching from the beginning, the $ is like the ^ but for pattern matching in the back.

As well, check out this url:

router.register(r'venue-filter-options-list/(?P<city>[a-zA-Z]+)'

Having the same problem with ^ and $ I am getting an error when I input a string into the city placeholder

if I put for example chicago into the city placeholder when calling the url in the browser

I get the following error in the django debug page:

Exception Type: ValueError

Exception Value:

invalid literal for int() with base 10: 'chicago'

that doesn't make any sense my regex is correct.

Anyone else have this issue?


Solution

    1. Viewsets are Class based and you'd need to call .as_view() in the url.
    2. You should specify methods as a dict to as_view()
    3. ViewSet get expects pk field to query by default, So if you want to use something else, you need to change the lookup field in the ViewSet declaration. The error is telling you that an int value the pk is required not a string. Read more from the doc http://www.django-rest-framework.org/api-guide/viewsets/