问题
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'),
回答1:
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'),
]
回答2:
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.
来源:https://stackoverflow.com/questions/48031043/how-to-have-options-in-urls-in-django-2-0