Ticket #6167: flatpages_append_slash.diff

File flatpages_append_slash.diff, 5.6 KB (added by Chris Beaven, 17 years ago)
  • django/contrib/flatpages/views.py

     
    11from django.contrib.flatpages.models import FlatPage
    22from django.template import loader, RequestContext
    3 from django.shortcuts import get_object_or_404
    4 from django.http import HttpResponse
     3from django.http import HttpResponse, Http404
    54from django.conf import settings
    65from django.core.xheaders import populate_xheaders
     6from django.core.urlresolvers import get_resolver
    77from django.utils.safestring import mark_safe
    88
    99DEFAULT_TEMPLATE = 'flatpages/default.html'
     
    2121    """
    2222    if not url.startswith('/'):
    2323        url = "/" + url
    24     f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID)
     24    try:
     25        f = FlatPage.objects.get(url=url, sites__id=settings.SITE_ID)
     26    except FlatPage.DoesNotExist:
     27        if url.endswith('/') or not settings.APPEND_SLASH:
     28            raise Http404
     29        # No matching flat page was found, but url didn't end in a slash and
     30        # APPEND_SLASH is on. Append a slash to the url and try to resolve that.
     31        resolver = get_resolver(getattr(request, 'urlconf', None))
     32        func, args, kwargs = resolver.resolve('%s/' % url)
     33        return func(request, *args, **kwargs)
    2534    # If registration is required for accessing this page, and the user isn't
    2635    # logged in, redirect to the login page.
    2736    if f.registration_required and not request.user.is_authenticated():
  • django/contrib/flatpages/tests.py

     
     1"""
     2Set up flat pages
     3>>> from django.contrib.flatpages.models import FlatPage
     4>>> from django.contrib.sites.models import Site
     5>>> site = Site.objects.get(pk=1)
     6>>> f = FlatPage.objects.create(url='/contact/', title='Contact Us',
     7...     content='Contact us at...', enable_comments=False)
     8>>> f.sites.add(site)
     9>>> f = FlatPage.objects.create(url='/custom/test', title='Custom flatpage',
     10...     content='similar to custom view', enable_comments=False,
     11...     template_name='custom_flatpage_template.htm')
     12>>> f.sites.add(site)
     13
     14Set up the resolver
     15>>> from django.core.urlresolvers import get_resolver, RegexURLResolver
     16>>> resolver = RegexURLResolver('^/', 'django.contrib.flatpages.tests')
     17>>> from django.http import HttpRequest
     18>>> fake_request = HttpRequest()
     19>>> fake_request.urlconf = 'django.contrib.flatpages.tests'
     20>>> def render(path):
     21...     func, args, kwargs = resolver.resolve(path)
     22...     return func(fake_request, *args, **kwargs).content
     23
     24Turn off APPEND_SLASH
     25>>> from django.conf import settings
     26>>> original_append_slash = settings.APPEND_SLASH
     27>>> settings.APPEND_SLASH = False
     28
     29Use test templates
     30>>> from django.contrib.flatpages.tests import TestTemplateLoader
     31>>> test_template_loader = TestTemplateLoader()
     32
     33Test a flat page
     34>>> print render('/contact/')
     35flatpage: Contact Us -- Contact us at...
     36
     37Flat pages can specify a custom template_name rather than using the default
     38'flatpages/default.html'.
     39>>> print render('/custom/test')
     40custom flatpage: Custom flatpage -- similar to custom view
     41
     42If a flat page is not found, Http404 is raised.
     43>>> print render('/nonexistant/')
     44Traceback (most recent call last):
     45  ...
     46Http404
     47>>> print render('/contact')
     48Traceback (most recent call last):
     49  ...
     50Http404
     51
     52Turn on APPEND_SLASH
     53>>> settings.APPEND_SLASH = True
     54
     55If a path is requested without a slash and it is caught by the flatpage view,
     56if no matching flat page is found (and APPEND_SLASH is True), a slash will be
     57added and then resolved again.
     58>>> print render('/contact')
     59flatpage: Contact Us -- Contact us at...
     60>>> print render('/custom/test')
     61custom flatpage: Custom flatpage -- similar to custom view
     62
     63We resolve again rather than just checking for another flat page because there
     64may be another view which should catch the path with appended slash.
     65>>> print render('/custom/notflatpage')
     66notflatpage
     67
     68Revert APPEND_SLASH and test templates
     69>>> settings.APPEND_SLASH = original_append_slash
     70>>> test_template_loader.revert()
     71"""
     72
     73from django.conf.urls.defaults import *
     74from django.http import HttpResponse
     75from django.contrib.flatpages.views import flatpage
     76from django.template import loader, TemplateDoesNotExist
     77
     78def custom_view(request, echo):
     79    return HttpResponse(echo)
     80
     81urlpatterns = patterns('',
     82    # A non-flatpage view
     83    url('^custom/(?P<echo>\w+)/$', custom_view),
     84    # Fall back to using flat pages
     85    url('(.*)', flatpage),
     86)
     87
     88class TestTemplateLoader:
     89    def __init__(self):
     90        self.register(test_template_loader)
     91    def register(self, *args):
     92        if not hasattr(self, 'old_template_loaders'):
     93            old_template_loaders = loader.template_source_loaders
     94        loader.template_source_loaders = args
     95    def revert(self):
     96        if hasattr(self, 'old_template_loaders'):
     97            loader.template_source_loaders = self.old_template_loaders
     98
     99templates = {
     100    'flatpages/default.html':
     101        'flatpage: {{ flatpage.title }} -- {{ flatpage.content }}',
     102    'custom_flatpage_template.htm':
     103        'custom flatpage: {{ flatpage.title }} -- {{ flatpage.content }}',
     104}
     105
     106def test_template_loader(template_name, template_dirs=None):
     107    "A custom template loader that loads the unit-test templates."
     108    try:
     109        return (templates[template_name], "test:%s" % template_name)
     110    except KeyError:
     111        raise TemplateDoesNotExist, template_name
     112
Back to Top