Reputation:
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 :)
Upvotes: 4
Views: 1007
Reputation: 12478
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.
Upvotes: 2
Reputation: 18999
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:
index
.path
argument; you may choose to name them differently.Upvotes: 0