include (some.urls)) i will not find any solution how to get the ur...">
include (some.urls)) - python 😸 💄 🧕

Django {% url%} when URLs with parameters like url (r '^ foo / <parameter> / $' include (some.urls))

i will not find any solution how to get the url in the template with the following configuration (using Django1.3):

urls.py

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

Url-conf enabled:

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 am trying to get the url in the template with:

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

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

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

+4
source share
2 answers

Yes, you can get your url like this: -

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

But note that your URL configuration should 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'), ) 

No foo-url unless you specifically specify: -

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 regex.

+3
source

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

in root urls

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 the template, you can simply enter:

{% url articles: read 1%}

or

{% url articles: publish%}

Read more about it here .

0
source

Source: https://habr.com/ru/post/1447836/


All Articles