I’m writing a Django website. It’s pretty much a read-only site, except for the administrator, who performs some update actions on it. I’d like the administrator to edit the site via its front end.
To support this, some URLs are displayed differently for the administrator, and some URLs should return 404 unless the request comes from the logged-in administrator.
I’d r开发者_如何转开发ather not make the existence of the administrator user particularly obvious to anonymous users, hence the 404s for admin-only pages if the user isn’t already logged in as the administrator.
My design for this at the moment is:
At the server level, have two hostnames as aliases for the same single Django site:
- admin.example.com
- www.example.com
At the Django app level, for every view that’s admin-only or is displayed differently for the administrator, check whether the request’s hostname is the
admin
one. If it is:- if the request comes from the logged-in administrator, return the page with the administrator-specific display
- otherwise, return 404
Have a URL that the administrator can go to manually to log in.
Is this dumb? Am I missing a simpler/better way to do this?
At the simplest level you can use the user_passes_test
decorator on your admin-specific views:
@user_passes_test(lambda u: u.is_superuser)
def only_admins_here(request):
#do stuff
Or you can simply branch in the view:
def some_view(request):
if request.user.is_superuser:
render_to_response('admin_template.html')
else:
render_to_response('template.html')
Creating a whole subdomain layer over this is going to get highly complicated quickly, since not all classes and functions in Django necessarily have access to the request object, and thus, which domain the request is coming from.
You can remove point one.
At the Django app level, for every view that’s admin-only or is displayed differently for the administrator, check whether the request comes from the logged-in administrator.
- if the request comes from the logged-in administrator, return the page with the administrator-specific display
- otherwise, return 404
- Have a URL that the administrator can go to manually to log in.
精彩评论