As the title explains, although I'm successfully logged in, I can't prevent the application from going back to the login page if I entered the path to the page in URL bar.
NOTE:I'm not using the built-in user or authentication classes.
Here is the code below:
class user_login_view(View):
form_class = LoginForm
template_name = 'main/login.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
username = request.POST['username']
password = request.POST['password']
if form.is_valid:
try:
member = user.objects.filter(username=username).first()
except user.DoesNotExist:
member = None
if member != None and member and member.password == password:
request.session['username'] = username
return redirect('main:index')
else:
messages.error(request,'account does not exist')
return render(request, self.template_name,{'form': form})
else:
messages.error(request, 'account does not exist')
return render(request, self.template_name,{'form': form})
def index(request):
template_name = 'main/loggedin.html'
if request.session.has_key('username'):
username = request.session['username']
return render(request, template_name, {"username" : username})
else:
return HttpResponseRedirect(reverse('main:login'))
def logout(request):
try:
del request.session['username']
except:
pass
return HttpResponseRedirect(reverse('main:login'))
Related
Why when i desactive user on Django admin site in my class in post method
requirement return negative first if requirement user is not None ?
Probably if user desative true Django don`t look him in user table ?
class LoginView(View):
template_name = 'login.html'
def get(self, request):
form = LoginForm()
return render(request, self.template_name, locals())
def post(self, request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('home')
else:
alert = messages.error(request, 'Twoje konto zostało zablokowane!')
return render(request, self.template_name, locals())
else:
alert = messages.error(request, 'Błędna nazwa użytkownika!')
return render(request, self.template_name, locals())
In authenticate function, django call authenticate on your AUTHENTICATION_BACKENDS in settings.py.
ModelBackend is a default authentication backend that has been provided by Django, and if you are using it, it checks if user is acive or not. It's sth like this:
def user_can_authenticate(self, user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
is_active = getattr(user, 'is_active', None)
return is_active or is_active is None
I am create a application where admin and customer login same browser.
I read many blog not able not fix my problem. As Django use session based login.
I am facing issue while logout my admin then my customer automatic logout. maybe session based functionally
My admin LoginView and Logoutview:
class AdminLoginView(SuccessMessageMixin,LoginView):
authentication_form = LoginForm
template_name = 'login.html'
redirect_field_name = reverse_lazy('admin_panel:dashboard')
redirect_authenticated_user = False
success_message = '%(username)s login Successfully !'
def dispatch(self, *args, **kwargs):
if self.request.user.is_authenticated:
# messages.info(self.request, f"{self.request.user.firstname} is already Logged In")
return redirect('/admin/dashboard/')
return super().dispatch(*args, **kwargs)
def get_success_url(self):
url = self.get_redirect_url()
LOGIN_REDIRECT_URL = reverse_lazy('admin_panel:dashboard')
return url or resolve_url(LOGIN_REDIRECT_URL)
class LogoutView(LogoutView):
"""
Log out the user and display the 'You are logged out' message.
"""
next_page = "/admin/login"
def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
messages.add_message(request, messages.INFO,'Successfully logged out.')
return response
I have implemented customer based login & logout
def LoginView(request):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data["remember_me"]
user = User.objects.get(email=username)
if user and user.check_password(password):
if user.is_active:
if remember_me == False:
request.session.set_expiry(0)
request.session['user_id'] = user.id
request.session['username'] = user.email
return HttpResponseRedirect('/')
else:
context = {'auth_error': "You're account is disabled"}
return render(request, 'forntend-signin.html', context )
else:
context = {
'auth_error': 'username and password incorrect'
}
return render(request, 'forntend-signin.html', context)
else:
context = {
"form": form
}
return render(request, 'forntend-signin.html', context)
def customer_logout(request):
try:
if request.session['username']:
del request.session['user_id']
del request.session['username']
else:
del request.session['user_id']
except KeyError:
HttpResponseRedirect("/")
return HttpResponseRedirect("/")
Please suggest me how to fix this issue.
If there any documentation available the please share.
So I am working on user authentication, login, logout. I am getting the error when I am opening the registration portal.
AttributeError at /profile/
'User' object has no attribute 'get_profile'
Following is my views.py
def Registration(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username = form.cleaned_data['username'],email = form.cleaned_data['email'] , password = form.cleaned_data['password'])
user.save()
UserProfile= UserProfile(user=user, birth_date=form.cleaned_data['birth_date',])
UserProfile.save()
return HttpResponseRedirect('/profile/')
else:
return render('visit/registration/register.html', {'form': form},)
else:
form= LoginForm()
context = {'form': form}
return render(request, 'visit/registration/register.html', context )
#login_required
def Profile(request):
if not request.user.is_authenticated:
return HttpResponseRedirect('/login/')
UserProfile = request.user.get_profile()
context ={'UserProfile': UserProfile}
return render(request,'visit/profile.html', context)
def LoginRequest(request):
if request.user.is_authenticated:
return HttpResponseRedirect('/profile')
if request.method == 'POST':
form = LoginRequest(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
UserProfile = authenticate(username=username, password=password)
if UserProfile is not None:
login(request, UserProfile)
return HttpResponseRedirect('/profile/')
else:
return render(request,'visit/registration/login.html',{'form':form})
else:
return render(request, 'visit/registration/login.html', {'form': form})
else:
form= LoginForm()
context = {'form': form}
return render(request, 'visit/registration/login.html', context, )
def logoutRequest(request):
logout(request)
return render(request, 'visit/login.html')
def index(request):
return render(request, 'visit/index.html', context=None)
I am not sure what/where the error is. I am using the Django 2.0.2.
I know there are similar questions but I am not getting the proper solution.
Help would be appricated. Following is my settings.py
#provides our get_profile
AUTH_PROFILE_MODULE = 'visit.model.UserProfile'
# URL for #login required
LOGIN_URL = '/login/'
#redirect authenticated user
LOGIN_REDIRECT_URL = '/profile/'
As per #neverwalker comment, this method is deprecated 1.7. please refer below code
user_profile = UserProfile.objects.get(activation_key='some_key')
user = user_profile.user
I'm trying to login but Django is not allowing the navigation to the profile.html
This is what I have so far
views.py
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
print(userObj)
username = userObj['username']
password = userObj['password']
user = authenticate(username=username, password=password)
if user is not None:
print("in login")
login(request)
return render(request, 'profiles.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
else:
return render(request, 'login_form.html')
forms.py
class UserLoginForm(forms.Form):
username = forms.CharField(
required=True,
label='Username',
max_length=32
)
password = forms.CharField(
required=True,
label='Password',
max_length=32,
widget=forms.PasswordInput()
)
Check This Code I have done login Register
https://github.com/gowthamand/django-1.11.5-crud-ajax-login-register
I used Inbuilt Login
I think that you need to pass the user to login function
from django.contrib.auth import authenticate, login as f_login
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
print(userObj)
username = userObj['username']
password = userObj['password']
user = authenticate(username=username, password=password)
if user is not None:
print("in login")
f_login(request, user)
return render(request, 'profiles.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
After creating a UserProfile model. I started to create login but I'm stuck because of get_user() error.
EXCEPTION
AttributeError: 'LoginForm' object has no attribute 'get_user'
Here are my codes:
UPDATE
class LoginView(FormView):
form_class = LoginForm
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'login.html'
success_url = '/'
def form_valid(self, form):
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(self.request, user)
return HttpResponseRedirect(self.get_success_url())
else:
return self.form_invalid()
def form_invalid(self):
return HttpResponseRedirect(reverse('accounts:login'))
def get_success_url(self):
if self.success_url:
redirect_to = self.success_url
else:
redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')
netloc = urlparse.urlparse(redirect_to)[1]
if not redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
elif netloc and netloc != self.request.get_host():
redirect_to = settings.LOGIN_REDIRECT_URL
return redirect_to
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid()
How to fix this? Any help would be appreciated. I'm really new on Django 1.5. Need help.
[update]
In the original code, the author is doing the authenticate stuff inside a form method called get_user. You are doing it outside the form already, so just replace form.get_user()with user.
I use a login view that is not class based, and I don't even care into using a Django form instance, but it should be easy to adapt:
def signin(request):
if request.method == 'POST':
user = authenticate(
email=request.POST.get('username', '').lower().strip(),
password= request.POST.get('password', ''),
)
if user is None:
messages.error(request, u'Invalid credentials')
else:
if user.is_active:
login(request, user)
return HttpResponseRedirect(request.GET.get('next', '/'))
else:
messages.error(request, u'User is not active.')
return render_to_response('login.html', locals(),
context_instance=RequestContext(request))
[old answer]
Define a get_user method for your form.
Untested (but should get you in the right path):
def get_user(self):
from django.contrib.auth import authenticate
return authenticate(
email=self.cleaned_data.get('username', '').lower().strip(),
password=self.cleaned_data.get('password', ''),
)