1

Why? I want multiple models on the first level of the path :)

Using: Django 1.4.1

Code setup urls:

PAGE_SLUGS = '|'.join(Page.objects.values_list('slug', flat=True))
BRAND_SLUGS = ... same concept
(r'^(?P<brand_slug>%s)/$' % BRAND_SLUGS, 'novomore.apps.catalog.views.product_showcase_list'),

url(r'^%s/$' % PAGE_SLUGS, 'prefab.apps.pages.views.page_detail', name='page'),

In the save method of model Page:

if self.pk is None:
    clear_url_caches()

I don't want to run a query on each request so thats why i use this aproach, when i add a instance the PAGE_SLUGS need to be updated.

clear_url_caches() doesnt seem to work

Any suggestions?

This doesn't do the trick:

if settings.ROOT_URLCONF in sys.modules:
    reload(sys.modules[settings.ROOT_URLCONF])
    reload(importlib.import_module(settings.ROOT_URLCONF))
Bas Koopmans
  • 341
  • 4
  • 14

2 Answers2

3

From How to reload Django's URL config:

import sys
from django.conf import settings

def reload_urlconf(self):
    if settings.ROOT_URLCONF in sys.modules:
        reload(sys.modules[settings.ROOT_URLCONF])
    return import_module(settings.ROOT_URLCONF)
dgel
  • 16,352
  • 8
  • 58
  • 75
  • Thanx for your answer, it still doesnt work; ive updated the post – Bas Koopmans Oct 15 '12 at 10:14
  • Due to the comments in http://codeinthehole.com/writing/how-to-reload-djangos-url-config/ on Django 1.4 it doesn't work? – Bas Koopmans Oct 15 '12 at 11:20
  • 2
    You might need to clear the url cache before reload the urls by using clear_url_caches(). – yunshi May 10 '17 at 07:43
  • 2
    I found this solution wasn't working for me because urls.py in the separate apps were also being changed dynamically, but `reload` on `settings.ROOT_URLCONF` only forces reloading on the the project main `urls.py`: not the app-level `urls.py` files. Therefore you may wish to iterate through your apps and reload each of their `urls.py`. – Silversonic Jul 06 '18 at 12:40
0

I don't think what you're trying to do is a good idea. Why not simply allow any slug pattern in the URL regex, but return a 404 if you can't find the Page in question? That would have the same effect and be much simpler.

url(r'^(?P<slug>\w+)/$', 'prefab.apps.pages.views.page_detail', name='page'),

then your view code can do something like

from django import shortcuts

def page_detail(request, slug):
    page = shortcuts.get_object_or_404(Page, slug=slug)
    ... 
DavidWinterbottom
  • 6,420
  • 5
  • 38
  • 39
  • Thats offcourse what im doing but i want multiple objects on the first level and not one or more querys for each incoming request .. Check my initial post, ive added a BRAND_SLUGS example – Bas Koopmans Oct 17 '12 at 08:45