如何在django 2.0中的url中有选项 [英] how to have options in urls in django 2.0

查看:42
本文介绍了如何在django 2.0中的url中有选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django 1中,我曾经有这样的网址选择:

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

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

我如何在Django 2.0中使用<>语法:

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

也许是这样吗?

path('meeting/(<action:edit|delete>)/', views.meeting_view, name='meeting'),

推荐答案

如果我理解文档,您的第一种语法应立即可用.

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:

第一个文件=制作一个Python包 converters ,然后添加 edit_or_delete.py :

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 ''

对于您的 urls.py 文件,这是

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'),
]

这篇关于如何在django 2.0中的url中有选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆