I want to update url pattern match with my product when I change database, so I using in urls.py:
main_cagetory_url=Product_category.objects.get_all_product_category_url()
main_cagetory_url_string = '(?:' + '|'.join(main_cagetory_url) + ')'
product_url=Product.objects.get_all_product_url()
product_url_string = '(?:' + '|'.join(product_url) + ')'
menu_url=Menu.objects.get_all_menu_url()
menu_url_string = '(?:' + '|'.join(menu_url) + ')'
urlpatterns = patterns('',
(r'^$',menu_page),
(r'^home_vi$',home_vi),
(r'^home_en$',home_en),
(r'^'+menu_url_string+'$',menu_page),
(r'^'+main_cagetory_url_string+'$',list_product),
(r'^'+product_url_string+'$',product_detail),
(r'^search_result$',search_result),
(r'^admin/', include(admin.site.urls)),)
Every thing ok when I’m developing in my pc. But when I uploadd my project to host. Every time I add new Product_category or Product. Django cannot realize that change and show 404 error when I click to new Product_category or new Product.
How can I fix that bug?
This started as a comment, but I thought I would try avoid creating a serial comment.
The reason this works in development mode is because the dev server automatically reloads any files (e.g. urls.py) that change. This doesn’t happen (and you don’t want it to happen) on a production server. I’ve never had a need to do this myself so I’m taking a hard look at the code & docs to see where the hooks may be.
Well after spending about 45 minutes on this my answer seems to be … you can’t do this, at least not easily. Note all line numbers below are from Django 1.3.1.
Django initializes your urls from the module named in your settings file as
ROOT_URLCONF, normallyurls. This initialization is somewhat expensive and Django goes out of its way to cache everything it can.In
BaseHandler.get_response()(django/core/handles/base.pyline 83)urlresolvers.set_urlconf()is called using the urls modules named insettings.ROOT_URLCONF. Effectively, this is global, hardwired knowledge about where the url configuration lives. Because of caching it only initializes your urls once per thread. That means that each thread in the web server that is handling your Django requests would need to be alerted to flush-and-initialize its urls every time there’s a database change, and that gets complicated all by itself.An alternative method would be to either create a super pattern that calls a view, which in turn makes a DB call. Another approach is to handle this in a middleware class where you test for a 404 error, check if the pattern is likely to be one of your categories, and then do the DB look up there. I have done this in the past and it’s not as bad as it sounds. Look at the
django/contrib/flatpagescode for a straightforward implementation of this approach.