Using the django admin's site authentication in a non-admin view
I am writing a simple django app to manage pages on a website. The pages are created through the admin site and can be previewed using the 'view on site' function. Each page has a 'published' boolean that determines whether the view that displays pages should show it on site. Of course, once I change the view to respect 'published' the admin page's 'view on site' link will not show the page either. But I want to be able to preview unpublished pages during the editing process.
So I decided to change the view to check whether there is an authenticated user associated with the request. For example:
if request.user.is_authenticated() and request.user.is_staff:
manager=Pages.objects #returns all pages
else:
manager=Pages.live #only returns published pages
Then the appropriate manager is passed to get_object_or_404 along with the page_id capt开发者_Go百科ured from the URL
However, in the view, user is always Anonymous even when a user who is authenticated with the admin site clicks the 'view on site' link. So the 'live' manager always gets used and I have the same result as before: 404 when unpublished pages are accessed from the admin site. Is this the way its supposed to behave? I really thought the session information would be inherited from the admin site's session.
I would appreciate any direction here because I may not be too clear on how this should work. I don't need a login mechanism for the site so I was hoping to piggyback off the admin's login to get the ability to view unpublished pages in the admin.
Thanks
The problem is gone. Now, if I am logged into admin I can view unpublished pages otherwise I get a 404 error.
Unfortunately, I'm not sure why it started working. I ran some package updates (neither django nor Firefox was among them) and had to restart my (archlinux) machine. When I restarted the django develpment server and tested the function again, all was well. I suspect Firefox was the culprit but that's only a guess.
Anyway, thanks to anyone who gave the issue some thought. I can stop pulling my hair out now.
精彩评论