11👍
For the forbidden (403) error, you could raise a PermissionDenied
exception (from django.core.exceptions
).
For the redirecting behaviour, there’s no built-in way to deal with it the way you describe in your question. You could write a custom middleware that will catch your exception and redirect in process_exception
.
5👍
I’ve made a little middleware that return whatever your Exception class’s render method returns. Now you can throw custom exception’s (with render methods) in any of your views.
class ProductNotFound(Exception):
def render(self, request):
return HttpResponse("You could ofcourse use render_to_response or any response object")
pip install -e git+http://github.com/jonasgeiregat/django-excepted.git#egg=django_excepted
And add django_excepted.middleware.ExceptionHandlingMiddleware
to your MIDDLEWARE_CLASSES
.
2👍
Django annoying has a solution for this:
from annoying.exceptions import Redirect
...
raise Redirect('/') # or a url name, etc
- Django docker – could not translate host name "db" to address: nodename nor servname provided, or not known
- Django admin.TabularInline auto insert three blank row
- Can I get expiration time of specified key in django cache?
- What are the default URLs for Django's User Authentication system?
- Catch all errors and display the type of error and message
1👍
You want to use decorators for this. Look up login_required
for an example. Basically the decorator will allow you check check the safety and then return HttpResponseRedirect()
if its not safe.
Your code will end up looking something like this:
@safety_check:
def some_view(request):
#Do Stuff
- In django + nginx + wsgi, what is a "mysite.sock"
- Dynamically loading django apps at runtime
- Django, REST and Angular Routes
- HttpResponse vs. Render