Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse url with optional fields arguments in django?

I have an url with an optionnal argument:

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?!

like image 785
christophe31 Avatar asked Aug 25 '11 12:08

christophe31


2 Answers

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
like image 133
programmersbook Avatar answered Nov 13 '22 18:11

programmersbook


Has to be this ticket:

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

like image 2
Jeff T Avatar answered Nov 13 '22 18:11

Jeff T