Login

Easier and Faster than flatpages. Rendering templates by simpling calling by his path on the URL

Author:
mariocesar
Posted:
February 29, 2012
Language:
Python
Version:
1.3
Score:
2 (after 2 ratings)

This is in my opinion a better way to have flat pages in a project. In the example with the url patterns settings:

/                 will render -> /pages/welcome.html
/contact          will render -> /pages/contact.html
/products/        will render -> /pages/products/index.html
/products/pricing will render -> /pages/products/pricing.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"""
views.py
"""

from django.views.generic.base import View
from django.template.response import TemplateResponse
from django.template.base import TemplateDoesNotExist
from django.http import Http404

class PageView(View):
    def get(self, request, *args, **kwargs):
        slug = kwargs['slug']
        # Fallback to search a index page if url ends with '/'
        slug = '%sindex' % slug if slug.endswith('/') else slug
        template = 'pages/%s.html' % slug
        response = TemplateResponse(request, template, {})

        # test if the template exists before the common middleware
        # try to automatically render the response
        try:
            response.resolve_template(template)
        except TemplateDoesNotExist:
            raise Http404('Page "%s" is not found' % slug)

        return response

"""
urls.py
"""

from django.conf.urls import patterns, url
from project.pages import views

urlpatterns = patterns('',
    url(r'^(?P<slug>.+)$', views.PageView.as_view()),
    url(r'^$', views.PageView.as_view(), {'slug':'welcome'}) # Easy to add aliases
)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

umbrae (on April 2, 2012):

Does this not have a path vulnerability in it? Slug could be ../../../../../etc/passwd for example.

#

Please login first before commenting.