Ticket #9847: 9847.diff

File 9847.diff, 7.6 KB (added by Steven L Smith, 14 years ago)

Added tests and docs... anyone care to test my tests?

  • django/conf/urls/defaults.py

     
    11from django.core.urlresolvers import RegexURLPattern, RegexURLResolver
    22from django.core.exceptions import ImproperlyConfigured
    33
    4 __all__ = ['handler404', 'handler500', 'include', 'patterns', 'url']
     4__all__ = ['handler403', 'handler404', 'handler500', 'include', 'patterns', 'url']
    55
     6handler403 = 'django.views.defaults.permission_denied'
    67handler404 = 'django.views.defaults.page_not_found'
    78handler500 = 'django.views.defaults.server_error'
    89
  • django/core/urlresolvers.py

     
    295295        except (ImportError, AttributeError), e:
    296296            raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, str(e)))
    297297
     298    def resolve403(self):
     299        return self._resolve_special('403')
     300
    298301    def resolve404(self):
    299302        return self._resolve_special('404')
    300303
  • django/core/handlers/base.py

     
    131131                        finally:
    132132                            receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
    133133            except exceptions.PermissionDenied:
    134                 return http.HttpResponseForbidden('<h1>Permission denied</h1>')
     134                try:
     135                    callback, param_dict = resolver.resolve403()
     136                    return callback(request, **param_dict)
     137                except:
     138                    return http.HttpResponseForbidden('<h1>403 Forbidden</h1>')
    135139            except SystemExit:
    136140                # Allow sys.exit() to actually exit. See tickets #1023 and #4701
    137141                raise
  • django/views/defaults.py

     
    11from django import http
    22from django.template import Context, RequestContext, loader
    33
     4def permission_denied(request, template_name='403.html'):
     5    t = loader.get_template(template_name) # You need to create a 403.html template.
     6    return http.HttpResponseForbidden(t.render(Context({'request_path': request.path})))
     7
    48def page_not_found(request, template_name='404.html'):
    59    """
    610    Default 404 handler.
  • tests/regressiontests/views/tests/debug.py

     
    11import inspect
     2from os import path, remove
    23
    34from django.conf import settings
    45from django.core.files.uploadedfile import SimpleUploadedFile
     
    3031        self.failUnless('file_data.txt' in response.content)
    3132        self.failIf('haha' in response.content)
    3233
     34    def test_403(self):
     35        # Can't use NamedTemporaryFile since it has to be in ../templates
     36
     37        # Create a 403.html and check if it is served to us when a 403 is triggered
     38        template_path = '../templates/403.html'
     39        if not path.exists(template_path):
     40            FILE = open(template_path)
     41            FILE.write('This is a test template for a 403 Forbidden error.')
     42            FILE.close()
     43        self.failIf(not path.exists(template_path)
     44        response_with_template = self.client.get('/views/raises403')
     45        self.assertEquals(response_with_template.status_code, 403)
     46        self.failUnless('template' in response_with_template.content)
     47        remove(template_path)
     48        self.failIf(path.exists(template_path))
     49
     50        # See if the default thing happens when a 403 is triggered, and we *don't* have a 403.html
     51        response_without_template = self.client.get('/views/raises403/')
     52        self.assertEquals(response_without_template.status_code, 403)
     53        self.failIf('template' in response_without_template.content)
     54
    3355    def test_404(self):
    3456        response = self.client.get('/views/raises404/')
    3557        self.assertEquals(response.status_code, 404)
  • tests/regressiontests/views/views.py

     
    66from django.views.generic.create_update import create_object
    77from django.core.urlresolvers import get_resolver
    88from django.shortcuts import render_to_response
     9from django.core.exceptions import PermissionDenied
    910
    1011from regressiontests.views import BrokenException, except_args
    1112
     
    4445    resolver = get_resolver(None)
    4546    resolver.resolve('')
    4647
     48def raises403(request):
     49    raise PermissionDenied()
     50
    4751def redirect(request):
    4852    """
    4953    Forces an HTTP redirect.
     
    5660def template_exception(request, n):
    5761    return render_to_response('debug/template_exception.html',
    5862        {'arg': except_args[int(n)]})
    59 
  • tests/regressiontests/views/urls.py

     
    109109urlpatterns += patterns('',
    110110    (r'^raises/$', views.raises),
    111111    (r'^raises404/$', views.raises404),
     112    (r'^raises403/$', views.raises403),
    112113)
    113114
    114115# rediriects, both temporary and permanent, with non-ASCII targets
  • AUTHORS

     
    430430    Ben Slavin <benjamin.slavin@gmail.com>
    431431    sloonz <simon.lipp@insa-lyon.fr>
    432432    Paul Smith <blinkylights23@gmail.com>
     433    Steven L. Smith (fvox13) <steven@stevenlsmith.com>
    433434    Warren Smith <warren@wandrsmith.net>
    434435    smurf@smurf.noris.de
    435436    Vsevolod Solovyov
  • docs/topics/http/views.txt

     
    196196That takes care of setting ``handler500`` in the current module. As you can see
    197197in ``django/conf/urls/defaults.py``, ``handler500`` is set to
    198198``'django.views.defaults.server_error'`` by default.
     199
     200The 403 (HTTP Forbidden) view
     201----------------------------
     202
     203In the same vein as the 404 and 500 views, Django has a view to handle 403 Forbidden
     204errors. If a view results in a 403 exception, Django will, by default, call the view
     205``django.views.defaults.permission_denied``, which loads and renders the template ``403.html``.
     206
     207If you do not provide a ``403.html`` template in your root template directory, this
     208view will instead serve the text "403 Forbidden", as per RFC 2616 (the HTTP 1.1 Specification).
     209
     210It is possible to override ``django.views.defaults.permission_denied`` in much the same way you
     211can for the 404 and 500 views.
  • docs/ref/exceptions.txt

     
    4848----------------
    4949
    5050The ``PermissionDenied`` exception is raised when a user does not have
    51 permission to perform the action requested.
     51permission to perform the action requested. It is equivalent to an HTTP 403 Error.
    5252
    5353ViewDoesNotExist
    5454----------------
Back to Top