How to display error when using is_active for Login - django

I set a user.is_active to false so they can't login.
user.is_active = False
user.save()
I would like to override the login section to show that the account has been disabled. Currently it shows on disabled accounts.
Please enter a correct username and password. Note that both fields may be case-sensitive.
I am using the auth login:
path('accounts/', include('django.contrib.auth.urls')),
With a simple template:
{% extends 'base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h2>Log In</h2>
<form method="POST" action="."enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log In</button>
<button>Sign up</button>
</form>
{% endblock %}
I have seen something like where they override clean and call this function.
def confirm_login_allowed(self, user):
if not user.is_active:
raise forms.ValidationError(
"This account has been disabled",
code='inactive',
)

from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
if user.is_active:
auth_login(request, user)
return redirect('home')
else:
messages.error(request,'User blocked')
return redirect('login')
else:
messages.error(request,'username or password not correct')
return redirect('login')
else:
form = AuthenticationForm()
return render(request, 'registration/login.html',{'form':form})
Just had to check is_active then send messages.error after overriding login.

Related

How can I show errors in the template like username is already taken?

How can I show errors like email or username is already taken in this page Aaccounts/sign-up.html because when try to to put a username and this username is already taken the page only refresh without any message.
Before:
After:
Code:
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'Aaccounts/sign-up.html'
def login (request) :
if request.method=='POST':
passwordtest=request.POST ['password']
usernametest=request.POST ['username']
user=auth.authenticate(username=usernametest,password=passwordtest)
if user is not None :
auth.login(request,user)
current_user = request.user
correctUSER = get_object_or_404(CustomUser, pk=current_user.id)
need_to_cheack=correctUSER.main_affilitee
kain=False
if need_to_cheack !="":
objs=CustomUser.objects.all()
for aleratwar in objs:
if kain==False:
if aleratwar.username==need_to_cheack and aleratwar.afilliteuser==True and aleratwar.username !=correctUSER.username :
kain=True
if kain== False:
correctUSER.main_affilitee=''
correctUSER.save()
return redirect('home')
else:
return render(request,'Aaccounts/login.html',{'eroor':True})
else:
return render(request,'Aaccounts/login.html')
This is the simple example of showing the message. In your view you can In this way
from django.contrib import messages
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
return redirect('index')
else:
messages.error(request,'username or password not correct')
return redirect('login')
else:
form = AuthenticationForm()
return render(request, 'todo/login.html', {'form': form})
{{ message }}
</div>
{% endfor %}
and In your template:
{% for message in messages %}
<div class="alert alert-success">
<a class="close" href="#" data-dismiss="alert">×</a>
{{ message }}
</div>
{% endfor %}

How to handle errors in django views?

I have a view to log in and when the user does not exist it throws me an error, I would like this error to be printed in the template, saying that the user does not exist, try this way but it does not work for me. Would there be any other way to make it work?
View
def login_rfid(request):
'''
Login
'''
if request.method == 'POST':
username = ''
if 'username' in request.POST:
print("sasrfwrfsrsf")
rfid = request.POST['username']
user = User.objects.get(rfid=rfid)
if user is not None:
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return redirect('/')
else:
messages.error(request, 'The user does not exist')
return render(request, "registration/login_rfid.html")
HTML
{% if messages %}
<div class="span12">
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message|safe }}
</div>
{% endfor %}
</div>
{% endif %}
ERROR
Ok i didnt understand why u wrote username=''
in beggining of the function but heres the code which will work for u
def login2(request):
# Check if the user is already logged in or not
if request.user.is_authenticated:
return redirect("/service-page.html")
if 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 redirect("/service-page.html")
else:
messages.error(request,"Invaild Credentials, Please try again")
return render(request,"login.html")
else:
return HttpResponse("Only POST Methods are allowed baby")
return HttpResponse("Wrong password")

Django template main.html it's not seeing user logged

hi i have a problem with login function in django ,when i loggin succes see when user is logged but main.html didnot .
wiews
def user_login(request):
context = {}
if request.method == "POST":
username = request.POST['username']
password = request.POST["password"]
user = authenticate(request,username=username,password=password)
if user.is_authenticated:
print("1")
login(request, user)
if request.GET.get('next',None):
print("2")
return HttpResponseRedirect(request.GET['next'])
return HttpResponseRedirect(reverse('success'))
else:
print("3")
context["error"] = "nieprawidlowe dane"
return render(request,'auth/login.html',context)
else:
print("4")
return render(request,'auth/login.html',context)
#login_required(login_url="/login/")
def success(request):
c = {}
c['user'] = request.user
return render(request,'auth/success.html',c)
and in here is succes and on this page django can see when user is logged
{% extends 'main.html' %}
{% block article %}
<p>User <b>{{ user.username }}</b> jestes zalogowony</p>
<form method="post" action="/logout/">
{% csrf_token %}
<input type="submit" value="Logout">
</form>
{% endblock %}
but main.html didnot see user

Django doesn't remember authenticated user

I have got a simple login function.
def login(request):
args = {}
args.update(csrf(request))
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('/')
else:
return redirect('/')
else:
return redirect('/')
And in my template, I use if statement to show some block only for authenticated users:
{% if username %}
<div class="container">
<div class="span6">Welcome!<strong> {{ username }}</strong></div>
{% endif %}
But when I am successfully logined, this block is not showed. I guess that the problem with redirect('/'). If it's so, I don't understand then: when I redirect to main page, then user is logged out?
For main page I use next view:
def index(request):
args = {}
args.update(csrf(request))
return render(request, 'index.html', args)
Use the user context variable to display the user's name. And the is_authenticated() method of the user instance should be used to determine the logged users from anonymous:
{% if user.is_authenticated %}
Welcome! <strong>{{ user.username }}</strong>
{% endif %}

Django. Error message for login form

I make login/password form:
model:
class LoginForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput(render_value=False),max_length=100)
view:
def login_view(request):
if request.method == 'POST':
username = request.POST['email']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect("/n1.html")# Redirect to a success page.
return HttpResponseRedirect("/login")
form=LoginForm()
return render(request, 'enter.html', {'login_form': LoginForm})
urls:
(r'^login/$', login_view),
template:
{% if form.errors %}
<p>Something is wrong</p>
{% endif %}
<form class="form-signin" action="" method="post">
<h2 class="form-signin-heading">Login</h2>
{% csrf_token %}
<input class="input-block-level" type="text" name="email" value="" id="email" placeholder="Email">
<input class="input-block-level" type="password" name="password" value="" id="username" placeholder="Password">
<button class="btn btn-large btn-primary" type="submit">Login</button>
<input type="hidden" name="next" value="{{next|escape}}" />
</form>
I use redirect to login page then login or password is wrong, but I want to make error message in this case. Why construction {% if form.errors %} doesn't work? Thx!
Because the form has no idea an error occurred.
When you construct the form here:
form=LoginForm()
You're constructing it without passing it any information. It doesn't know anything about the POST the user just did, or that the the login failed, or that the password was missing, or whatever the error was.
Here's what my login forms look like:
class LoginForm(forms.Form):
username = forms.CharField(max_length=255, required=True)
password = forms.CharField(widget=forms.PasswordInput, required=True)
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if not user or not user.is_active:
raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
return self.cleaned_data
def login(self, request):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(username=username, password=password)
return user
We override the form's clean method, so that if the form passes validation we can check the user's credentials. We also put a login method on the form object itself, to make our view cleaner.
Next, in our view, we want to do this:
def login_view(request):
form = LoginForm(request.POST or None)
if request.POST and form.is_valid():
user = form.login(request)
if user:
login(request, user)
return HttpResponseRedirect("/n1.html")# Redirect to a success page.
return render(request, 'enter.html', {'login_form': form })
We instantiate the form and hand it the request.POST to check against.
If we have a POST, we check if the form is valid. The form's "clean" method will get called, and check the user credentials for us.
If the credentials fail, we raise an error, which we need to show in our template.
Errors raised by the form (but not attached to a field) are stored in non_field_errors, which can be displayed like so:
{% if form.non_field_errors %}
<ul class='form-errors'>
{% for error in form.non_field_errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
When you redirect, I'm not sure you send the context of your page. So when you redirect to the /login/ page, django tinks it's a new form which is loaded.