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 %}
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.
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")
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
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})