Django - decorators and error messages
This seems like a simple question but I can't seem to find a simple answer. Django seem开发者_StackOverflows to give this nifty simple way of limiting access to places using the permission required or login required decorators but I can't see from the Django docs how one would pass an error message (maybe using the messages framework). If I have to roll my own decorator to do this, what is the point of the django decorators? Do they just not show any error messages?
I think you're conflating security and permissions with Django's authentication system. For the most part, Django's tools are mainly designed for separating users into two groups: authenticated (logged in), and anonymous. This makes sense for 90% of the web sites out there, as you don't really need too much differentiation (maybe another for a hidden admin, but that's an edge case, rather than the norm).
The permission_required decorator is a very simple hook for people wishing to redirect people who failed to have permissions to go to the login page. At some point, though, this is not enough. If you need a specific permission and the user does not have it, how does redirecting them to the login page help them?
In this case, it's so easy to roll your own decorator using the messages for specific errors. One such example:
def user_has_permissions(method):
return user_passes_test(lambda u: u.has_perm('my_permission'), login_url='/permission-denied/')(method)
You will send the user an automatic error message.. You'd have to look how to over-ride..
I'll assume you simply avoided reading this
http://docs.djangoproject.com/en/1.2/topics/auth/#the-login-required-decorator
login_required() does the following:
If the user isn't logged in, redirect to
settings.LOGIN_URL
, passing the current absolute path in the query string. Example:/accounts/login/?next=/polls/3/
.If the user is logged in, execute the view normally. The view code is free to assume the user is logged in.
There are no "error messages". Error messages are rude. And largely useless. They're often a sign of bad design.
Generally, you don't need a million tiny little explanations. Indeed, the default login page works fine for 80% of the use cases. If you need to clarify the situation, you can provide your own HTML form. You can use the ordinary template context to add additional information. You have the Messages Framework for presentation of extra messages on the login page.
精彩评论