Sunday, November 30, 2014

template url reverse and namespacing is driving me crazy

Alright, I'm already crazy, so the subject is a bit of a lie. But nevermind.

I think I like namespacing, it is really nice. But there is something not that clear in the documentation of Django, and how to make usage of namespace, in a consistent way. Lets take it by example.

I'm using this pretty amazing app "greeter" that was written by a superuser from a country far away from my own. It is a pretty simple app, that has two url mappings:

url(r'^list/$', HelloWorldList.as_view(), name='list'),
url(r'^greet/(?P<pk>\d+)/$', HelloWorldGreet.as_view(), name='greet'),

The template of HelloWorldList view is using the template tag url like this: {% url 'greet' greeter.pk %}.

After that I hook up the application in my project by including it in my project urls.py:

url(r'^greeter/', include('greeter.urls')),

Everything works well, I felt like a Django guru integrating the hello world app to my own project. I can access /greeter/list and clicking on the greetings works well.

Later that night I go to bed, feeling confident, kissing my wife goodnight with a smile on my face. I wake up warm, sweaty, with my heart beating. I run to my laptop, just realized I forgot to namespace the greet app, because I just realized I am using the list name in another place in my project, and I don't have any automated tests, so I better namespace it quickly.

So, I change my project url mapping to this:

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

Boom crash. Visiting the /greeter/list/ page gives me:

Reverse for 'greet' with arguments '()' and keyword arguments '{pk:1}' not found. 0 pattern(s) tried: []

I start to doubt the author of the 'greeter' app, that he didn't prepare his app for being used in other projects, where the project might need namespacing to avoid conflicts.

Digging into Django documentation, I don't really find any argument for the author of the 'greeter' app to be sloppy and not caring of details.

Someone who can enlighten me why django doesn't try to default to the current app when resolving namespaces? Or can someone enlighten me how I can help out the author of the 'greeting' app, so it really is reusable in other projects?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4106d7ca-06aa-4d5e-8094-4370f116a167%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment