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)
Related
So the goal is for a new user to register an account and then get redirected to the home page and recognized. So that the user does not have to register for their account then go through the process of logging in right after. I want a standard registration, like Instagram, Twitter, and other professional applications.
So far, I'm where the user can register and redirect them to the homepage, but when I try to print their name on the screen, I get AnonymousUser. The user's information is written to the database after registering, but Django doesn't know who the user is. For Django to know who is logged in after registering, they have to log out and then log in right after registering their account. If anyone could help, I would be much appreciated it.
Views.py
from django.shortcuts import render, redirect
from .forms import RegisterForm
from django.contrib import messages
def register(response):
if response.method == "POST":
form = RegisterForm(response.POST)
if form.is_valid():
form.save()
return redirect("/")
else:
form = RegisterForm()
return render(response, "register/register.html", {"form": form})
Using the authenticate() and login() functions:
from django.contrib.auth import authenticate, login
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
messages.info(request, "Thanks for registering. You are now logged in.")
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
)
login(request, new_user)
return HttpResponseRedirect("/dashboard/")
originally answered
after successful registration POST REQUEST explicitly log in the users using the login method and you can access the name of the user without having the user to login again...
I am using the django-email-verification app and I had to change how a User is signed up but I left the login authentication part the same. Every time I try to login it does not allow me to sign in and says that the credentials are wrong. Also I used emails as usernames. I'm thinking its the:
user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
that needs to be changed. Please how do I fix the login?
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib.auth import get_user_model
from django_email_verification import sendConfirm
def signup(request):
if request.method == 'POST':
if request.POST['pass1'] == request.POST['pass2']:
try:
user = User.objects.get(username=request.POST['username'])
return render(request, 'accounts/signup.html', {'error': 'Email is already registered'})
except User.DoesNotExist:
'''user = User.objects.create_user(request.POST['username'], password=request.POST['pass1'])
auth.login(request, user)'''
user = get_user_model().objects.create(username=request.POST['username'], password=request.POST['pass1'], email=request.POST['username'])
sendConfirm(user)
return redirect('home')
else:
return render(request, 'accounts/signup.html', {'error': 'Passwords must match'})
else:
return render(request, 'accounts/signup.html')
def login(request):
if request.method == 'POST':
user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
auth.login(request, user)
return redirect('home')
else:
return render(request, 'accounts/login.html',{'error':'username or password is incorrect.'})
else:
return render(request, 'accounts/login.html')
def logout(request):
if request.method == 'POST':
auth.logout(request)
return redirect('home')
The problem is not with authenticating, but with creating the user. Passwords are normally hashed. The .create(…) function [Django-doc] will not hash these, you can make use of .create_user(…) [Django-doc] instead:
user = get_user_model().objects.create_user(
username=request.POST['username'],
password=request.POST['pass1'],
email=request.POST['username']
)
The .create_user(…) function is a function the manager of the user model normally should provide. This will for (most) user models store the hash of the password in the database.
I want to redirect to different pages based on the login credentials in django.
For an example: There are two login provided
If i login with X credentials then i will be redirected to X page. While on same login page if i login with Y credential i will be redirected to correponding Y page.
I tried to put condition in user_login views.py file but this gives me following error.
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'companyDashboard.html' not found. 'companyDashboard.html' is not a valid view function or pattern name.
My views.py file
from django.shortcuts import render
from django.template import RequestContext
from wfhApp.forms import UserForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def company_dashboard(request):
return render(request, 'wfhApp/company_dashboard.html')
#login_required
def companyDashboard(request):
return render(request, 'wfhApp/companyDashboard.html')
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('index'))
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username= username, password=password)
if user:
if user.is_active:
if user.username == 'prashant':
login(request, user)
return HttpResponseRedirect(reverse('company_dashboard.html'))
elif user.username == 'saurabh':
login(request, user)
return HttpResponseRedirect(reverse('companyDashboard.html'))
else:
return HttpResponse("Account Not Exists")
else:
return HttpResponse("Account Not Active")
else:
print("Someone tried to login and failed")
print("Username: {} and Password: {}".format(username, password))
return HttpResponse("Invalid Login Details")
else:
return render(request, 'wfhApp/login.html')
Thank you for your time and consideration.
Check out urlresolvers docs, to use reverse you must set name in path (urls.py). Don´t add .html extension, use the setted name at urls.py.
from news import views
path('archive/', views.archive, name='news-archive')
Use the setted name.
# using the named URL
reverse('news-archive')
# passing a callable object
# (This is discouraged because you can't reverse namespaced views this way.)
from news import views
reverse(views.archive)
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 am now working on a system using the Django framework. I am writing the user login part. It seems successful but it doesn't work very well.
The login system can recognise the user by his/her username and password.
The authentication could only last for one "webpage". When I loaded another page or even reloaded the page, django can't get the info of the user(seems logged out)
If I looked at the page resources, I saw a session number made after the login process.
What should I do to ensure only one login is needed? And keep my user logged in during the whole process?
Here is my view file
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext, loader
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render_to_response,redirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.template.context_processors import csrf
from . import models
from . import form as f
from django.contrib.sessions.backends.db import SessionStore
def index(request):
if request.user != None :
template = loader.get_template('index.html')
return HttpResponse(template.render(None))
else :
return HttpResponseRedirect('/PDT/login_failed')
def Home(request):
template = loader.get_template('Home.html')
return HttpResponse(template.render(None))
def loggin_in(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def login_user(request):
logout(request)
username = password = ''
if request.POST:
username = request.POST.get('username','')
password = request.POST.get('password','')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
request.session['username']=user.username
return HttpResponseRedirect('/PDT/logged_successful')
return HttpResponseRedirect('/PDT/inactive')
return HttpResponseRedirect('/PDT/incorrect')
return HttpResponseRedirect('/PDT/login_failed')
def logged_in(request):
if request.user :
return render_to_response('index.html',{ 'user' : request.user },context_instance=RequestContext(request))
else :
return HttpResponseRedirect('/PDT/login_failed')
def login_failed(request):
return render_to_response('problem.html',{ 'message' : "Login failed" })
def log_out(request):
request.session.flush()
logout(request)
return render_to_response('problem.html',{ 'message' : "Logged out" })
def inactive(request):
return render_to_response('problem.html',{ 'message' : "Inactive" })
def incorrect(request):
return render_to_response('problem.html',{ 'message' : "Incorrect Username or Password" })
def iter_update(request):
if request.session['username'] != None :
return render_to_response('iter_update.html',{ 'user' : request.user },context_instance=RequestContext(request))
else :
return HttpResponseRedirect('/PDT/login_failed')
def Create_form(request):
if request.method == "POST":
form = f.ProjectForm(request.POST)
if(form.is_valid()):
print(request.POST['title'])
form.save()
message = 'success'
else:
message = 'fail'
return render_to_response('Create_form.html',
{'message': message,
'user': request.user,},
context_instance=RequestContext(request))
else:
return render_to_response('Create_form.html',
{'form': f.ProjectForm()},
context_instance=RequestContext(request))
Please use return render(request, template_name, context_dict) to render templates. Your peculiar way probably strips it of context.
Also, take a look at this decorator, and use it instead of your current if request.user != None : statements.
Your user is logged in, but because you are strangely rendering the Home and Index templates via template.render(None), there is no request or user context in your template. Instead, use the render shortcut which runs context processors.