django logout and redirection - django

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

Related

Django user login error using User authentication()

I have a basic login, sign up html page in my Django project: the login page redirects to the user_login function in views.py as follows:
<form action="{% url 'user_login' %}" method="POST">. //rest of the code
In urls.py the request is getting forwaded correctly:
.......#beginnning code
path('user_login', views.user_login, name='user_login'),
path('portfolio', views.portfolio, name='portfolio'),
......
In views.py this is my user_login code to authenticate the user and redirect the user to a 'portfolio.html' page if the user credentials are correct.
I have imported User, Login class as follows:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .models import Profile
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
# Create your views here.
def index(request):
return render(request, 'mysite/index.html')
def user_login(request):
if request.method == 'POST':
name_r = request.POST.get('name')
password_r = request.POST.get('password')
user = authenticate(username=name_r, password=password_r)
if user:
login(request, user)
#below line might be incorrect
return HttpResponseRedirect('mysite/portfolio.html')
else:
return render(request, 'mysite/login.html')
#rest of the code for signup which is working perfectly.
Whenever i click on Login page, the login page never loads in the first place, let alone checking whether authentication is taking place or not.
The error occurring is as follows:
I am not sure exactly where the error is occurring and what solution must be applied to it.
Your view never returns anything if request.method is not POST.

Django Authentication process

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.

django.contrib.auth.logout in Django

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

How to let the user know that they have logout in django?

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

Django permission_required error message?

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.