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

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

Related

Trying to render two different views in one template according to their specific url routing

Im trying to render login and register view in a single template using variable assignment and if-else. I'm sorry if its a rookie mistake, Im pretty new to this..
github repo- https://github.com/varundhand/DevSearch
my urls.py :-
urlpatterns = [
path('login/',views.loginUser,name='login'),
path('logout/',views.logoutUser,name='logout'),
path('register/',views.registerUser,name='register'),
path('',views.profiles,name='profiles'),
path('profile/<str:pk>/',views.userProfile,name='user-profile'),
]
my views.py :-
def loginUser(request):
page = "login"
if request.user.is_authenticated:
return redirect('profiles')
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
try:
user = User.objects.get(username=username)
except:
messages.error(request,'Username doesnt exist')
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect ('profiles')
else:
messages.error(request,'Username/Password incorrect')
context = {page:'page'}
return render(request, 'users/login_register.html', context)
def logoutUser(request):
logout(request)
messages.error(request,'User was logged out!')
return redirect('login')
def registerUser(request):
page = "register"
context= {page:'page'}
return render(request,'users/login_register.html', context)
my html template file :-
{% extends 'main.html' %}
{% block content %}
{% if page == "register" %}
<h1>Register User</h1>
<p>Already have an account? Login </p>
{% else %}
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<input type="text" name="username" placeholder="Username">
<input type="pass`your text`word" name="password" placeholder="Enter Password">
<input type="submit" value="Login">
<p>Dont have an account? Sign Up</p>
</form>
{% endif %}
{% endblock content %}
My Approach
I gave variable assignment of page='login' and page='register' in loginUser and registerUser view respectively and then i gave an if-else in my common template but for some reason only loginUser view is working even when i go to the register url.
Ignore my silly question, I was passing the wrong context dictionary i.e. it shoulda been context = {'page':page}

How to display error when using is_active for Login

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 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")

How to Fix UnboundLocalError at /signup/ in Django

I Want To Create A User Like Signup or register when i hit submit button i got this error:
UnboundLocalError at /signup/
i want to signup user:
local variable 'usercustom' referenced before assignment
here is my Views.py
def signup(request):
registered = False
if request.method == "POST":
user_form = UserForm(request.POST or None)
custom_form = UserCustom(request.POST or None)
if user_form.is_valid() and custom_form.is_valid():
user = user_form.save(commit=False)
user.save()
custom = custom_form.save(commit=False)
custom.user = user
custom.save()
registered = True
else:
print(user_form.errors,custom_form.errors)
else:
user_form = UserForm()
usercustom = UserCustom()
return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered})
here is my Form.html
{% extends "base.html" %}
{% block body_block %}
<div class="content-section">
{% if registerd %}
<h1>Thank Your For registering!</h1>
{% else %}
<h1>Register Here</h1>
<h3>Fill out the form</h3>
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
{{ usercustom.as_p }}
<input type="submit" value="Register!" class="btn btn-danger">
</form>
{% endif %}
</div>
{% endblock %}
It is because usercustom is not declared when you tried to send POST request. You need to rename custom_form variable to usercustom. I have simplified your code for you.
def signup(request):
registered = False
if request.method == "POST":
user_form = UserForm(request.POST or None)
usercustom = UserCustom(request.POST or None)
if user_form.is_valid() and usercustom.is_valid():
user = user_form.save(commit=False)
user.save()
custom = usercustom.save(commit=False)
custom.user = user
custom.save()
registered = True
else:
print(user_form.errors, usercustom.errors)
else:
user_form = UserForm()
usercustom = UserCustom()
return render(request,'form.html',{'user_form':user_form,'usercustom':usercustom,'registered':registered})

Django Form Errors Won't Display

I've built a "firewall" login form that I want to put in front of my
actual production website while I develop the site. The idea is to try
and keep the "bad guys" out of the site and at the same time see what
usernames and passwords they're using. The problem I'm having is that
if I enter an invalid username/password pair, my form's error message
doesn't get displayed. I realize that for my purposes, it it might be
better to not display any error message at all but I'd still like to
understand what the problem is. Can anyone see what I'm doing wrong?
Thanks.
# views.py
import logging
logger = logging.getLogger(__name__)
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import login
from django.http import HttpResponseRedirect
def firewall_login(request, *args, **kwargs):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
username = request.POST['username']
password = request.POST['password']
if form.is_valid():
fw_username = form.cleaned_data['username']
fw_password = form.cleaned_data['password']
user = authenticate(username=fw_username, password=fw_password)
if user is not None:
if user.is_active:
login(request, user)
logger.info("User '%s' logged in." % fw_username)
return HttpResponseRedirect("/accounts/profile/")
else:
logger.info("User '%s' tried to log in to disabled account." % fw_username)
return HttpResponseRedirect("/accounts/disabled/")
else:
logger.info("User '%s' tried to log in with password '%s'." % (username, password))
form = AuthenticationForm(request) # Display bound form
else:
form = AuthenticationForm() # Display unbound form
return render(request, "registration/login.html", {"form": form,})
# login.html
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<p class="alert alert-error">Sorry, that's not a valid username or password</p>
{% endif %}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for field in form.non_field_errors %}
<div class="alert alert-error">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<form action="" method="post">
{% csrf_token %}
<p><label for="username">Username:</label>{{ form.username }}</p>
<p><label for="password">Password:</label>{{ form.password }}</p>
<input type="hidden" name="next" value="{{ next|escape }}" />
<input class="btn btn-primary" type="submit" value="login" />
</form>
{% endblock %}
It's because you pass new form instance. Validation occurs on is_valid call.
So, just remove form = AuthenticationForm(request) in else block:
def firewall_login(request, *args, **kwargs):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
username = request.POST['username']
password = request.POST['password']
if form.is_valid():
fw_username = form.cleaned_data['username']
fw_password = form.cleaned_data['password']
user = authenticate(username=fw_username, password=fw_password)
if user is not None:
if user.is_active:
login(request, user)
logger.info("User '%s' logged in." % fw_username)
return HttpResponseRedirect("/accounts/profile/")
else:
logger.info("User '%s' tried to log in to disabled account." % fw_username)
return HttpResponseRedirect("/accounts/disabled/")
else:
logger.info("User '%s' tried to log in with password '%s'." % (username, password))
else:
form = AuthenticationForm() # Display unbound form
return render(request, "registration/login.html", {"form": form,})