I have this view function that needs to send a flash message to a user when they sign up. Now that is running well but the problem is that I set an error message to show when the username or password is incorrect and its always showing there by default. Here is my code
views.py
def signup(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, 'An account was created for ' + user)
return redirect('login')
def login_user(request):
username = request.POST.get('username')
password =
request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Incorrect Username or Password')
And when I go to the login page its just showing me incorrect username or password even though I just got there
How can I make it to show only when the username or password is incorrect
after mesasge.info redirect to again login page
messages.info(request, 'User not exist')
return redirect('login')
in html file
{% for message in messages %}
<div style="width: 350px; margin-left:500px; " class="alert alert-{{ message.tags }} " id="msg" role="alert">
{{ message }}
{% endfor %}
Related
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 %}
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")
I have 2 login page - login_admin and login_user for admin and normal user respectively.
When user enter username and password in login_admin and login_user page, it will check whether user is_staff is True or False.
If user is_staff = True, then allow the user login admin page.
My problem is: The user can't login to admin page although is_staff = True. The user is able to login to normal user page although is_staff = True. I don't know where is the problem.
Here is my code in views.py:
def login_admin(request):
context = {}
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
if username and password:
user = authenticate(username=username, password=password)
if user:
if request.user.is_staff:
login(request, user)
return redirect('/home/')
else:
context['error'] = "You are authenticated but are not authorized to access this page. Would you like to login to a different account?"
return render(request, 'registration/login.html',context)
else:
context['error'] = "Invalid username or password!"
return render(request, 'registration/login.html',context)
return render(request, 'registration/login.html')
def login_user(request):
context = {}
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
if username and password:
user = authenticate(username=username, password=password)
if user:
if not request.user.is_staff:
login(request, user)
return redirect('/cust/home/')
else:
context['error'] = "Invalid username or password!"
return render(request, 'registration/custlogin.html',context)
else:
context['error'] = "Invalid username or password!"
return render(request, 'registration/custlogin.html',context)
return render(request, 'registration/custlogin.html')
login.html
{% extends 'base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h2>Admin Login Screen</h2>
Customer Login Page
<form method="post">
{% csrf_token %}
<table cellpadding="10">
<tr>
<td><label for="usename">Username: </label></td>
<td><input type="text" name="username" id="username" required></td>
</tr>
<tr>
<td><label for="password">Password: </label></td>
<td><input type="password" name="password" id="password" required></td>
</tr>
<p style="color:red; font-weight: bold">{{ error }}</p>
</table>
<button type="submit" class="btn btn-primary">Login</button>
</form>
{% endblock %}
url.py
url(r'accounts/login/', customers.views.login_admin,name='login_admin'),
url(r'accounts/custlogin/', customers.views.login_user,name='login_user'),
url(r'accounts/logout/', customers.views.logout_user,name='logout_user'),
UPDATED:
I'm not able to sign in to admin page when is_staff = True / False which will return error You are authenticated but are not authorized to access this page. Would you like to login to a different account? which is written in my code, but able to sign in to user page when is_staff=True / False.
If i remove if user.is_staff, it works for admin and normal user.
urls.py
url(r'^accounts/login/$', customers.views.login_admin,name='login_admin'),
url(r'^accounts/custlogin/$', customers.views.login_user,name='login_user'),
url(r'^accounts/logout/$', customers.views.logout_user,name='logout_user'),
UPDATED V2:
I've tried the code that written by #Rarblack but still get error : 'QuerySet' object has no attribute 'is_staff'.
So I've modified the code and it works.
from django.contrib.auth.models import User
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
if username and password:
user = authenticate(username=username, password=password)
if user:
user_instance = User.objects.filter(Q(username_exact=username) & Q(is_staff=True))
if user_instance:
login(request, user)
return redirect('/home/')
else:
....
As seen from your code you are getting password and username from the login form and your implementation of it is not correct. You should have used django form or ModelForm and get the input from cleaned_data dict. It should have been something like this:
if request.method == 'POST':
form = ExampleForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data'password']
if username and password:
user = authenticate(username=username, password=password)
......
When we come to your issue, the problem is in this part:
if not request.user.is_staff:
login(request, user)
return redirect('/cust/home/')
what you are basically is doing letting non-staff users in. Change it to:
if request.user.is_staff:
login(request, user)
return redirect('/cust/home/')
EIDT: You are missing request part in the authenticate() method also try this:
user = authenticate(request, username=username, password=password)
if user:
if not user.is_staff:
The problem is that you cannot check any user's staff status because at that time there is no any user logged in to check. So request.user will not return a user. But you can try this:
from django.contrib.models import User
from django.shortcuts import get_object_or_404
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
if username and password:
user = authenticate(username=username, password=password)
if user:
user_instance = User.objects.filter(username_exact=username)
if user_instance.is_staff:
login(request, user)
return redirect('/home/')
else:
....
You use if not request.user.is_staff: in both views. For login_admin, if you only want staff to be able to log in, you should change it to:
if request.user.is_staff:
I use UserCreationForm to render registration form in Django.
class RegisterForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields
The registration view is defined as follows:
def register(request):
form = RegisterForm()
if request.method == 'POST':
form = RegisterForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
else:
context = {'form': form}
return render(request, 'registration/register.html', context)
And the template for this:
{% if form.errors %}
<p>Some Errors occured</p>
{% endif %}
<form action="{% url 'register' %}" method="POST">
{% csrf_token %} {{ form.as_p }}
<input type="submit" value="Register">
</form>
When I submit invalid data, it does not show <p>Some Errors occured</p>, but throws
Exception Type: ValueError
Exception Value:
The view myapp.views.register didn't return an HttpResponse object. It returned None instead.
which means I have to return HttpResponsein the 2nd if/else statement. The other forms work fine and show form.error messages, except this one. What is the problem? Thanks.
form = RegisterForm(request.POST or None, request.FILES or None)
first of all you dont wanna an empty field in your register form so you dont wanna user or None . second you are using request.FILES while you have no FileField in your form . i fixed your form
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/')
else:
form = RegisterForm()
return render(request, 'registration/register.html',{'form': form})
You need to move the last line back one indent, so it is run both in the case that the request is not a POST and also when it is a POST but the form is not valid.
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 %}