开发者

django urlpatterns from sql

I am trying to create urlpatterns with sql query, but this will work only for those things that already was in sql table at the moment of server start. If it possible to make django to check for new开发者_开发技巧 urls dynamically from database?

I know, this can be done with regular expressions, but they are too greedy, I mean, that i need to make this at root level of my site and regexp will "eat" all matching names and this regexp must be the last of urlpatterns list.


Going on your comment to pyeleven's answer, it seems you have understood the point of urlpatterns. You don't need or want to specify the choices of your section in the urlconf. What you do is grab the value of each section of the url, and pass that as a parameter to the view. So, for example:

(r'^?P<section>\w+)/$', 'my_view')

This will grab urls like /name1/ and /name2/, and pass name1 and name2 to the view as the section parameter. So there's no need to change the code whenever you add a section.


Although this is the nastiest, most un-django-esque thing imaginable, you can get your urls from the db, if you really, really want to:

models.py:

from django.db import models

class Url(models.Model):
    name = models.CharField(max_length=20)

urls.py:

from my_app.models import Url

urls = []
for url_object in Url.objects.all():
    urls.append(url(url_object.name, 'my_view'))

urlpatterns = patterns('my_app.views', *urls)

Voilà. It actually works. Url patterns directly from the db. Please don't do this.

I'm going to go take a shower now.


Have you checked django flatpages?

http://docs.djangoproject.com/en/dev/ref/contrib/flatpages/?from=olddocs

Dynamic url might not be such a good idea, for example a bad url line added dynamically might make the server stop functioning.

Can you elaborate on your goals?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜