views:

110

answers:

3

If there is a painless way of runtime urlconf modifications? e.g. based on database records?

Bruteforce soluttion:

r('^(.*)/', handmade_router_function)

is too brutal for me :)

Thanks in advance!

UPD: I understand that i can directly modify urlpatterns from my code, but it is requires a lot of hand-coding (custom admin-save actions, delete handlers etc). and i want to figure out if there is a ready to use app/library :)

A: 

Have you tried modifying the "urlpatterns" variable at runtime?

MikeN
Yes, it works, but requires dozens of hand-coding (e.g. overriding admin save-handlers, watching if url was deleted etc)Just wondering if there is 3rd party app/library that can help me :)
Anatoly Kudinov
A: 

Something like this works. You will be iterating over something different, such as model instances as you mentioned, but the premise is the same:

for path in ["foo", "bar"]:
    urlpatterns += patterns("myapp.views", url(r"^%s/$" % path, "index", {}, name=path))

I placed this code in my urls.py. This results in the following being mapped to the view:

http://127.0.0.1:8000/foo/
http://127.0.0.1:8000/bar/

Some things to note:

  1. I am not sure what your views are, so this just calls a view named index.
  2. I name the URLs after their respective path argument; you may choose to name them differently.
Ryan Duffield
i`ve update description to clarify the question
Anatoly Kudinov
+1  A: 

There is a contrib app in Django that already does this, it is called FlatPages. It works by registering a middleware. When a page is requested if it is not found it throws a 404 which is caught by the middleware. The middleware looks up the page in the database if found it serves the page and if not it throws a 404.

Jason Christa
Thanks! exactly what i want ATM :)
Anatoly Kudinov