5

i don't find any solution, how to get the url in template with the following configuration (using Django1.3):

urls.py

urlpatterns = patterns('',
    url(r'^/foo/(?P<parameter>\d+)/$', include('bar.urls'), name='foo-url'),
    )

Included url-conf:

bar.urls.py

urlpatterns = patterns('',
    (r'^/bar/$', 'bar.views.index'),
    url(r'^/bar/(?P<parameter2>\d+)/$', 'bar.views.detail', name='bar-url'),
    )

bar.views.py

def detail(request, parameter, parameter2):
    obj1 = Foo.objects.get(id=parameter)
    obj2 = Bar.objects.get(id=parameter2)

Now I try to get the url in template with:

{% url bar-url parameter=1 parameter2=2 %}

I expect to get: /bar/1/foo/2/

Is it posible to use in this case the {% url %}?

2 Answers 2

4

Yes, you can get your url like this:-

{% url 'bar-url' 1 2 %}

But note that your url configuration should actually be like this:-

urls.py

urlpatterns = patterns('',
    url(r'^/foo/(?P<parameter>\d+)/, include('bar.urls')),
)

bar.urls.py

urlpatterns = patterns('',
    (r'^/bar/$, 'bar.views.index'),
    url(r'^/bar/(?P<parameter2>\d+)/$, 'bar.views.detail', name='bar-url'),
)

There is no foo-url unless you specifically map:-

urls.py

urlpatterns = patterns('',
    url(r'^/foo/(?P<parameter>\d+)/$, 'another.views.foo', name='foo'),
    url(r'^/foo/(?P<parameter>\d+)/, include('bar.urls')),
)

Note that $ means the end of the regular expression.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the hint. I got it working now. I make some mistakes when setting the parameter in the url-tag. I use version 1.3, therefor {% url bar-url 1 2 %} works.
0

Well, I usually set namespace for included urls to simplify the process:

in root urlpatterns

url(r'^articles/', include('articles.urls', namespace='articles')),

in articles/urls.py

url(r'^(\d+)/$', 'read', name='read'),

url(r'^publish/$', 'publish', name='publish'),

And then in your template you can simply type:

{% url articles:read 1 %}

or

{% url articles:publish %}

More about this here.

1 Comment

I'm trying to use namespaces, but it seems not to work with a parameter before the included urls.py. See stackoverflow.com/questions/13788062/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.