I have used the following code snippet to logout the user from the session.
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')
Question> I need to notify the user that he/she has successfully logout. How can I do that in django?
Thank you
i guess you could redirect them to a thanks for logging out page instead of /
you may also want to have a look at the messages framework
Related
I have various applications in a Django project, but I only want users who are logged in to be able to access those pages. How can I restrict access to every pages except the login page which is my main page. For instance, mywebsite.com/home/user should be only available to user and if someone types in that it should redirect them to mywebsite.com
Currently I have two apps, main and Home, I am using ClassBased views on my Home app how can I restrict access to all my pages except login page and show a message as well?
I want to create a template that users can see other user profile details but not change or edit them. How can I do those above steps
Thanks in advance!
According to Docs you can decorate the class based views with #login_required
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
#method_decorator(login_required, name='dispatch')
class ClassBasedView(View):
...
...
Since you are using class based view, you need to add method decorator, else you can use #logine_required directly.
And the other part in the question is again a separate one from this.
You can try This, In very simple way
from django.contrib.auth.decorators import login_required
#login_required
def my_view(request):
return HttpResponse()
using #login_required means user have to login to access that view
Or If you you Want to use class then try this
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class RestrictedView(LoginRequiredMixin, TemplateView):
template_name = 'foo/restricted.html'
raise_exception = True
permission_denied_message = "You are not allowed here."
i am using django authentification to make a oneToone relation with the user table. I try to use decorator #login_required to the next page after the login. when i logout and click on the back button of firefox, i always go to the previous page even if #login_required is apply. but when i refresh it redirect me on the login page. Is it a cache problem? how can i solve it? I want to do it like how the administration works
def logout(request):
from django.contrib.auth import logout
from django.shortcuts import redirect
logout(request)
request.session.flush()
return redirect('/')
from django.contrib.auth.decorators import login_required
#login_required(login_url='/')
def administration(request):
do something
return something
I noticed that when I logged in as administrator, I don't need to reauthenticate when I access non-admin area.
However, when I login as simple user and access admin zone, Django, of course, checks whether I am admin.
Where this check occurs? I want to restrict access of moderators to non-admin part of site, so need to check that.
Thank you.
Use the #user_passes_test decorator:
from django.contrib.auth.decorators import user_passes_test
def not_staff_user(user):
return not user.is_staff
#user_passes_test(not_staff_user)
def my_view(request):
...
If you want to restrict ALL pages except /admin/ then middleware is a good option:
from django.conf import settings
from django.shortcuts import redirect
class NonStaffMiddleware(object):
def process_request(self, request):
if request.user.is_staff and not \
(request.path.startswith('/admin/') or
request.path.startswith(settings.LOGIN_URL) or
request.path.startswith(settings.LOGOUT_URL)):
return redirect(settings.LOGIN_URL)
You have the user.is_staff, user.is_superuser and user.is_authenticated functions to check this wether in your views or templates. If you need to do this in your templates, the user is in the {{ request.user }} and also in your views with request.user.
I would like to use the logout function from Django but not sure how to use it properly.I have been referring to this Django User Authenication: https://docs.djangoproject.com/en/dev/topics/auth/ and it reads
from django.contrib.auth import logout
def logout_view(request):
logout(request)
# Redirect to a success page.
The confusing part for me is the # Redirect to a success page. How do i redirect it to another page. Should I use HttpResponseRedirect or add additional arguments to logout(request). I am not sure what to do.. Need some guidance.
Django has a shortcut method called redirect. You could use that to redirect like this:
from django.contrib.auth import logout
from django.shortcuts import redirect
def logout_view(request):
logout(request)
return redirect('home')
Where home is the name of a url pattern you defined in urls.py like this:
urlpatterns = patterns('',
url(r'^$', 'blah.views.index', name='home'))
)
In the redirect call you could use a path as well, like / to redirect to the site root, but using named views is much cleaner.
PS: the code posted by #Hedde is from django.contrib.auth.views module, logout method. If that's what you want to use, you can import it like this:
from django.contrib.auth.views import logout
You don't have to write a view for that, you can just do:
(r'^accounts/logout/$', 'django.contrib.auth.views.logout',{'next_page': '/accounts/login'})
More info: https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.views.logout
Look at the source of the logout method, it should give you a clear idea what's going on. You can add extra arguments to the logout method to handle redirecting, but you can also append after the method for custom behaviour
def logout(request, next_page=None,
template_name='registration/logged_out.html',
redirect_field_name=REDIRECT_FIELD_NAME,
current_app=None, extra_context=None):
"""
Logs out the user and displays 'You are logged out' message.
"""
auth_logout(request)
redirect_to = request.REQUEST.get(redirect_field_name, '')
if redirect_to:
netloc = urlparse.urlparse(redirect_to)[1]
# Security check -- don't allow redirection to a different host.
if not (netloc and netloc != request.get_host()):
return HttpResponseRedirect(redirect_to)
#etc...
def logout(request):
# Log out the user.
logout(request)
# Return to homepage.
return HttpResponseRedirect(reverse('registeration:index'))
urlpatterns =[
path('accounts/logout/', views.LogoutView.as_view(template_name="post_list.html"), name='logout'),
]
write a template_name as above inside it worked for me.Hope it might be useful.
Thankyou
I've added this decorator to one of my views
#permission_required('codename')
When a user visits that page and doesn't have the required permissions, he is redirected the login page, but it doesn't really tell him why he's been redirected there. Worse yet, if he logs in, and still doesn't have the permissions, he's going to be completely clueless as to why he can't access that page!
Isn't there a way I can tap into the messages framework and post an error at the same time?
Not sure what version of Django you are using, but in Django 1.4 and higher you can use:
from django.contrib.auth.decorators import permission_required
#permission_required('app.permission',raise_exception=True)
def myView(request):
#your view code
This will raise a 403 exception and if you have a 403.html page at the base of your template folder it will server this out.
If you are using class based views:
from django.views.generic.base import View
from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator
class MyView(View):
#method_decorator(permission_required('app.permission',raise_exception=True)
def get(self, request):
#your GET view
Hope this helps.
You can tap into the messages framework and provide an error message. See my answer to an identical question.
You could use login_url parameter in this decorator to redirect to some other page, rather than login page. Or you can simply write your own decorator based on the code from django:
def permission_required(perm, login_url=None):
"""
Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary.
"""
return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)
Simply change login_url to some redirect_to and it won't cause any confusion.
Use #permission_required_or_403('codename')
This will redirect the users to a 403 'permission denied' error page.