开发者

URLs stored in database for Django site

开发者 https://www.devze.com 2022-12-08 05:24 出处:网络
I\'ve produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py.

I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py.

Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have 开发者_StackOverflow中文版a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... so on, so on. I also have a column for the URL. How do I get Django to call the information in the database table from the URL stored in the column rather than having to code a view and the URL for every page (which obviously defeats the purpose of a CMS)?

If someone can just point me at the right part of the docs or a site which explains this it would help a lot.

Thanks all.


You dont have to to it in the flatpage-way

For models, that should be addressable, I do this:

In urls.py I have a url-mapping like

  url(r'(?P<slug>[a-z1-3_]{1,})/$','cms.views.category_view', name="category-view")

in this case the regular expression (?P<slug>[a-z1-3_]{1,}) will return a variable called slug and send it to my view cms.views.category_view. In that view I query like this:

@render_to('category.html')
def category_view(request, slug):
    return {'cat':Category.objects.get(slug=slug)}

(Note: I am using the annoying-decorator render_to – it is the same as render_to_response, just shorter)

Edit This should be covered by the tutorial. Here you find the url-configuration and dispatching in every detail. The djangobook also covers it. And check pythons regex module.

Of course you can use this code.


Your question is a little bit twisted, but I think what you're asking for is something similar to how django.contrib.flatpages handles this. Basically it uses middleware to catch the 404 error and then looks to see if any of the flatpages have a URL field that matches.

We did this on one site where all of the URLs were made "search engine friendly". We overrode the save() method, munged the title into this_is_the_title.html (or whatever) and then stored that in a separate table that had a URL => object class/id mapping.ng (this means it is listed before flatpages in the middleware list).

0

精彩评论

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