Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top