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.
- One custom view, set on handler403 variable at project urls.py
- Render 403.html template
- Render one hard-coded template
To use Middleware, follow instructions:
- Download the project tgz at end of this article. We use this project as example and I called it of http403project.
- Unpack and copy file http.py to some place of your project, in http403project project I put in project root.
- Add the middleware to settings.py:
MIDDLEWARE_CLASSES = ( # ... 'http403project.http.Http403Middleware', )
- Raise a Http403 exception in view, ex:
from http import Http403 def Http403View(request): raise Http403(u"This is custom message for permission denied.")
- 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 urls.py
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: https://github.com/chronossc/http403 … It have Thomas updates.