Manipulando erros Http 403 (permissão negada) no Django

24 Nov

Hello people. Recently I used Django Auth module and his permission system. Is very interesting how we can define custom permissions per model and use in view, templates, etc.

Today, our code come from necessity of easily work with forbidden urls, where Django give us only HttpResponseForbidden class, that isn’t really interesting to handle, once that ideal is something like Http404 exception.

Based on this necessity, I developed a Middleware that intercept Http403 exceptions, and return, in following order, one of options:

  1. One custom view, set on handler403 variable at project
  2. Render 403.html template
  3. Render one hard-coded template

To use Middleware, follow instructions:

  1. Download the project tgz at end of this article. We use this project as example and I called it of http403project.
  2. Unpack and copy file to some place of your project, in http403project project I put in project root.
  3. Add the middleware to
          # ...
  4. Raise a Http403 exception in view, ex:
    from http import Http403
    def Http403View(request):
      raise Http403(u"This is custom message for permission denied.")
  5. Configure your custom view or template if want. Your template should be named 403.html. Your custom view should receive request and exception arguments. Exception argument for view transport custom message that user raised, you can view a simple example in http403project

Project tgz: http403project.tgz

Ok, that’s it. Use is very simple, be happy 😉

Update: Thomas Grainger ask for a licensed version, and also put code on gist. To do things right way, I put code in a repository in git: … It have Thomas updates.

VN:F [1.9.22_1171]
Rating: 4.0/5 (1 vote cast)

2 Responses to “Manipulando erros Http 403 (permissão negada) no Django”

  1. Thomas Grainger March 23, 2012 at %I:%M %p #

    I created a version of this to use in my project:

    can you explicitly release this into the Public Domain? or under some other license compatible with the APL eg the WTFPL

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

Leave a Reply