如何在django中使用可选字段参数反转url?

时间:2022-06-01 20:30:26

I have an url with an optionnal argument:

我有一个带有optionnal参数的url:

urlpatterns = patterns(
    'my_app.views',
    url('schedule/(?P<calendar_id>\d+)/(?:month(?P<relative_month>[\+,\-]\d)/)$',
    'attribute_event',name='attribute_event')
)

In my template I have a link:

在我的模板中,我有一个链接:

{% url attribute_event calendar.id %}

But I have an error saying the url can't be reversed with these args. Must I use 2 url regex entry and url names?!

但我有一个错误,说这些arg无法逆转网址。我必须使用2个url正则表达式和url名称吗?!

2 个解决方案

#1


6  

only possible if you split it into two urls:

只有将它拆分为两个网址才有可能:

urlpatterns = patterns('my_app.views',
    url('schedule/(?P<calendar_id>\d+)/month(?P<relative_month>[\+,\-]\d)/$',
        'attribute_event', name='attribute_event_relative'),
    url('schedule/(?P<calendar_id>\d+)/)$', 
        'attribute_event', name='attribute_event'),
)    

in template:

在模板中:

{% url attribute_event calendar.id %}

or

{% url attribute_event_relative calendar.id '+1' %}

your view:

你的观点:

def attribute_event(request, calendar_id, relative_month=None):
    pass

#2


2  

Has to be this ticket:

必须是这张票:

https://code.djangoproject.com/ticket/9176

https://code.djangoproject.com/ticket/9176

#1


6  

only possible if you split it into two urls:

只有将它拆分为两个网址才有可能:

urlpatterns = patterns('my_app.views',
    url('schedule/(?P<calendar_id>\d+)/month(?P<relative_month>[\+,\-]\d)/$',
        'attribute_event', name='attribute_event_relative'),
    url('schedule/(?P<calendar_id>\d+)/)$', 
        'attribute_event', name='attribute_event'),
)    

in template:

在模板中:

{% url attribute_event calendar.id %}

or

{% url attribute_event_relative calendar.id '+1' %}

your view:

你的观点:

def attribute_event(request, calendar_id, relative_month=None):
    pass

#2


2  

Has to be this ticket:

必须是这张票:

https://code.djangoproject.com/ticket/9176

https://code.djangoproject.com/ticket/9176