Login code:
def login(request):
if request.method == 'POST':
user = request.POST['uname']
password = request.POST['psw']
log = User.objects.filter(username=user, password=password)
if log:
request.session['login'] = True
return HttpResponseRedirect('/page')
else:
return render(request, 'login.html')
else:
return render(request, 'login.html')
Logout code:
del request.session['login']
request.session.modified = True
return HttpResponseRedirect("/")
After logout when I move back I am able to see the previous pages but as soon as I refresh the page it redirects me to login page and restricts me to access previous page.
def page(request):
if not request.session.get('login', False):
return HttpResponseRedirect("/tnp_admin/")
else:
#access page
How to not display previous pages after logout and why is session working only after refreshing page?
You can either use if user.is_authenticated in the view or import login_required property from django.contrib.auth.decorators and put #login_required on top of your view for that template.
Related
This Is My code of login in Django Application
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate,logout,login
from django.contrib.auth.decorators import login_required
from SedHelper.settings import LOGIN_URL
from .models import HelperApps
# Create your views here.
def Login(request):
if request.method == 'GET':
if request.user.is_authenticated:
logout(request)
return render(request,'login.html')
elif request.method == 'POST':
username=request.POST['username']
password=request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return render(request,'login.html',context=error)
# No backend authenticated the credentials
def logout_view(request):
print(request.user.is_authenticated)
if request.user.is_authenticated:
logout(request)
return redirect(Login)
def home(request):
#load all data from db(10)
if request.user.is_authenticated:
posts=HelperApps.objects.all()[:11]
return render(request,'dashboard.html',{'posts':posts})
else:return redirect(Login)
I just wanted to Logout when ever someone refresh the Page .In entire Application where ever someone refresh the the page it should logout immidiately.Anyone please.
i am also new to stackoverflow Please try to ignore the mistakes.
Create a Middleware, and write this function:
def logout_when_refresh(request):
logout(request)
Like in facebook. after logging in users are prompted to user homepage. but it prevents the logged in users to going back to login page unless users logout. so how to prevent the logged in users from going back after loggin in
def register(request):
form = self.register_form(request.POST)
if request.method=='POST':
if form.is_valid():
user = form.save(commit=False)
firstName=form.cleaned_data.get('firstName')
lastName=form.cleaned_data.get('lastName')
username=form.cleaned_data.get('username')
email=form.cleaned_data.get('email')
password=form.cleaned_data.get('password1')
user.set_password(password)
user.save()
messages.success(request, f'Account successfully created!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'registration/register.html', {'form': form})
path('login/', auth_views.LoginView.as_view(template_name='registration/login.html',redirect_authenticated_user=True), name='login'),
# path('logout/', auth_views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'),
path('register/', views.register, name='register'),
LOGIN_REDIRECT_URL = 'home:index'
LOGIN_URL = 'login'
LOGOUT_REDIRECT_URL = 'index'
Below are some option. try reading django doc https://docs.djangoproject.com/en/2.1/topics/auth/
Option 1
This can be one of the way. You check if the user is logged in and return suitable html page.
views.py
def home(request):
if not request.user.is_anonymous:
return render("home.html")
else:
return render("login.html")
Option 2
Check if the user is logged in , if so redirect to home page endpoint
from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth import login_required
def login(request):
if not request.user.is_anonymous:
return HttpResponseRedirect('/home')
#login_required
def home(request):
# Render you home page response
What you can do is redirect the user to the home page even if the user clicks the login/signup link.
For this you can do something in the login and signup views:
def login(request):
# if the user is already logged in, redirect to user home page
if request.user.is_authenticated:
# redirect to the home page
else:
# do something like defining get or post method request conditions
def signup(request):
# if the user is already logged in, redirect to user home page
if request.user.is_authenticated:
# redirect to the home page
else:
# do something like defining get or post method request conditions
This is one way to redirect the logged in user to the home page even if the user clicks the login/signup link or tries going back to the login page.
when create page opens up, even if i don't fill any information ,it does'nt gives me the error all fields are required , rather every time it logs me out and goes to home page. I think my if(request.method==post) block is not processed at all,rather it logs me out , and takes me back to my signup/home page
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from .models import Product
from django.utils import timezone
def home(request):
return render(request,'products/home.html')
#login_required
def create(request):
if request.method == 'POST':
if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']:
product = Product()
product.title=request.POST['title']
product.body=request.POST['body']
if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
product.url=request.POST['url']
else:
product.url= 'http://'+ request.POST['url']
product.icon=request.FILES['icon']
product.image=request.FILES['image']
product.pub_date= timezone.datetime.now()
product.hunter=request.user
product.save()
return redirect('create')
else:
return render(request,'products/create.html',{'error':'All fields are required'})
else:
return render(request,'products/create.html')
Did you log in with your user? You'd need to do have a separate view function which will authenticate your user and keep the user logged in to a session. Suggesting this since I don't see any login view function or any reference on how you're logging in your app.
EDIT: How to login using django (from the docs)
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
else:
# send a message to show user is not logged in
pass
I have created a login system. The view is as follows:
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = form.get_user()
login(request,user)
return redirect('home:index')
else:
form = AuthenticationForm()
return render(request,'accounts/login.html',{'form':form})
And I added a login_required decorator to the home page as follows:
#login_required(login_url="/login/")
def index(request):
return render(request, 'home/index.html', context)
The problem is that when I access the index page with localhost:8000/home/, the page is redirected correctly to the login page. But with 127.0.0.1:8000/home/ the home page is rendered and I am not redirected to the login page!
Any solution?
Thanks in advance!
This probably happen because you are already logged in in 127.0.0.1 domain
Try to clear your cookies or logout to solve that
I want to redirect user to the main page after login. In my template, I have this,
Login and Work
The problem is the user won't be redirected to the main page after login, the settings.LOGIN_REDIRECT_URL will take over and redirect the user to the url I specified in the settings file.
How can I make Django make use of my ?next url set in the template instead of forcefully using settings.LOGIN_REDIRECT_URL?
Here is example how you can do it in the login view. Pay attention to the REDIRECT_FIELD_NAME:
def login(request, login_form=AuthenticationForm, template_name='accounts/login.html',
extra_context=None):
form = login_form()
if request.method == 'POST':
form = login_form(request.POST, request.FILES)
if form.is_valid():
identification, password, remember_me = (form.cleaned_data['identification'],
form.cleaned_data['password'],
form.cleaned_data['remember_me'])
user = authenticate(identification=identification, password=password)
if user.is_active:
signin(request, user)
redirect_to = login_redirect(request.GET.get(REDIRECT_FIELD_NAME), user)
return HttpResponseRedirect(redirect_to)
else:
return redirect(reverse('profile_disabled', kwargs={'username': user.username}))
if not extra_context: extra_context = dict()
extra_context.update({
'form': form,
'next': request.GET.get(REDIRECT_FIELD_NAME),
})
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request)