4

In Django 1 I used to have url choices like this:

url('meeting/(?P<action>edit|delete)/', views.meeting_view, name='meeting'), 

How I do this in Django 2.0 with the <> syntax:

Maybe something like this?

path('meeting/(<action:edit|delete>)/', views.meeting_view, name='meeting'),
Atma
  • 29,141
  • 56
  • 198
  • 299
  • You can use `re_path` https://docs.djangoproject.com/en/2.0/ref/urls/#re-path – neverwalkaloner Dec 30 '17 at 04:57
  • @neverwalkaloner If you have to write your own `re_path` instead of being able to use the syntax right out-of-box like it was the case with `1.x` version, this is not an improvement in Django 2, but a regression. I hope there's a better way! – Olivier Pons Dec 30 '17 at 10:33

2 Answers2

4

If I understand the documentation, your first syntax should work right out-of-the-box.

Anyway here's how you could do with the new syntax:

First file = make a Python package converters and add edit_or_delete.py with that:

import re

class EditOrDeleteConverter:
    regex = '(edit|delete)'

    def to_python(self, value):
        result = re.match(regex, value)
        return result.group() if result is not None else ''

    def to_url(self, value):
        result = re.match(regex, value)
        return result.group() if result is not None else ''

And for your urls.py file, this:

from django.urls import register_converter, path

from . import converters, views

register_converter(converters.EditOrDeleteConverter, 'edit_or_delete')

urlpatterns = [
    path('meeting/<edit_or_delete:action>/', views.meeting_view, name='meeting'),
]
Olivier Pons
  • 15,363
  • 26
  • 117
  • 213
1

I would not use verbs in urls to indicate the purpose. Rather, rely on HTTP verbs such as GET, PUT, POST, DELETE and handle them in your view. That way, you can have just one view class handling all those different methods with just one URL.

Jason
  • 11,263
  • 21
  • 87
  • 181