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")
Related
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.
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 %}
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've been working on Django Authentication, but I have stumbled on a problem: login works on a page (the "post detail" page of the blog), but not on the homepage.
This is the part of the base.html that handles this header
{% if user.is_authenticated %}
<span class="glyphicon glyphicon-plus"></span>
<span class="glyphicon glyphicon-edit"></span>
<p class="top-menu">Hello, {{ user.first_name }}!<small> (Log out)</small></p>
{% else %}
<form>
{% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
{{ login_form.as_p }}
</form>
{% endif %}
The view seems good to me, anyway here it is
def login(request):
if request.method == 'POST':
login_form = CustomLoginForm(request.POST)
email = request.POST.get('email')
password = request.POST.get('password1')
user = authenticate(email=email, password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
return HttpResponseRedirect('/')
else:
return HttpResponse("Your Blog account is disabled.")
else:
print "Invalid login details: {0}, {1}".format(email, password)
return HttpResponse("Invalid login details supplied. Get back to the homepage.")
else:
login_form = CustomLoginForm()
return render(request, 'blog/post_list.html', {})
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
user = CustomUser.objects.all()
user_form = CustomUserCreationForm()
login_form = CustomLoginForm()
return render(request, 'blog/post_list.html', {'posts': posts, 'user_form': user_form, 'login_form': login_form, 'user': user})
I think the core of the problem could be on either the header of the base.html file or on the view.
This is what I see on the homepage (even when I'm logged in)
This is what I see on the post-detail page (and that's what I should see on the homepage too)
Any thoughts?
Your problem is here:
user = CustomUser.objects.all()
and then
return render(request, 'blog/post_list.html',
{'posts': posts, 'user_form': user_form,
'login_form': login_form, 'user': user})
You are passing a queryset result consisting of CustomUser objects as user in your request context. It overwrites the user variable assigned by the django.contrib.auth.context_processors.auth context processor.
To solve the problem, simply change the name of the template variable to something else, such as:
return render(...
'users': 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 %}