Django urls straight to html template

后端 未结 5 1940
我在风中等你
我在风中等你 2021-02-01 01:58

Learning django & python.

Just set up a new site after doing the tutorial. Now for arguments sake say I want to add a bunch of About us, FAQ basic html pages with ve

5条回答
  •  [愿得一人]
    2021-02-01 02:55

    Write a url which grabs the static pages you're interested in

    url(r'^(?Pabout|faq|press|whatever)/$', 'myapp.staticpage', name='static-pages')
    

    The staticpage view function in myapp

    from django.views.generic.simple import direct_to_template
    from django.http import Http404
    
    def staticpage(request, page_name):
        # Use some exception handling, just to be safe
        try:
            return direct_to_template(request, '%s.html' % (page_name, ))
        except TemplateDoesNotExist:
            raise Http404
    

    Of course, you need to follow a naming convention for your templates, but this pattern can be expanded upon as needed.

    This is better than the .+\.html pattern because it will treat templates which don't exist as 404s, whereas .+\.html will blow up with 500 errors if the template doesn't exist.

提交回复
热议问题