Login anonymous behaviour even though the user exist it shows invalid user - django

views.py
'
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("inactive")
else:
return HttpResponse("Someone tried to login and failed")
else:
return render(request, 'basic_app/login.html', {})
login.html
{% extends 'basic_app/base.html' %}
{% block content %}
<div class="jumbotron">
<form action="{% url 'basic_app:user_login' %}" method="POST">
{% csrf_token %}
<label for="username">USERNAME</label>
<input type = "text" name="Username" placeholder="enter">
<label for="password">Password</label>
<input type = "password" name="password" placeholder="PASSWORD">
<input type = "submit" name ="" value = "LOGIN">
</form>
</div>
{% endblock %}
In django admin the users are registered and are in database but when i login it shows Someone tried to login and failed .
I have to submit this by midnight need help noob here.

Related

How can i Register and Login In The Same Page in Django?

i would like to have both my login form and my registration form on the same page within the same template, so i would like to have them under one view function but i am not too sure on how i can do that, here is my code.
Views.py
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST) == "Register"
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request,"Account was Created for " + user)
context = {'form':form}
return render(request,'login.html',context)
def login(request):
if request.method == "POST":
if request.POST.get('submit') == 'Login':
username = request.POST.get('username')
password = request.POST.get('password1')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request,user)
return redirect('shop.html')
else:
messages.info(request, 'Wrong Username or password')
context = {}
return render(request,'shop.html',context)
login.html
<div class="formBx">
<form method="POST",name="Login",value="Login">
{% csrf_token %}
<h2>Sign In</h2>
{{form.username}}
{{form.password1}}
<input type="submit" name="submit" value="Login">
<p class="signup">Don't have an Account?Sign Up.</p>
{% for message in messages %}
<p id="messages">{{message}}</p>
{% endfor %}
</form>
</div>
</div>
<div class="user signUpBx">
<div class="formBx">
<form method="POST" value="Register">
{% csrf_token %}
<h2>Create an account</h2>
{{form.username}}
{{form.email}}
{{form.password1}}
{{form.password2}}
<input type="submit" name="submit" value="Register">
<p class="signup">Already Have an Account?Sign In.</p>
{% for message in messages %}
<p id="messages">{{message}}</p>
{% endfor %}
</form>
</div>
I'm getting AttributeError at /login/
'bool' object has no attribute 'is_valid' error right now.
You can use two separate forms for login and register in same view. Here is an example:
def register_login(request):
if "register" in request.method == "POST": #add the name "register" in your html button
..... your registration code
if "login" in request.method == "POST": #add the name "login" in your html button
..... your login code
**html**
<form>
{%csrf_token%}
.... your registration form
<button type="submit" name="register">register</button>
</form>
<form>
{%csrf_token%}
.... your login form
<button type="submit" name="login">register</button>
</form>

Can't login in the view Django

i can't create view for login. I try to login as created superuser, but i can't.
I tried create user via admin panel, but i can't login too as that user.
login_view function:
def login_view(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
print('successful')
else:
print('failed')
return render(request, 'login.html')
login.html:
<body>
{% if request.user.is_authenticated %}
<p>You are logged</p>
{% else %}
<form class="w-50 mx-auto" method="POST">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Enter password" name="password">
</div>
<button type="submit" class="btn btn-primary">Log in</button>
</form>
{% endif %}
</body>
input tag type should be username. And auth request should be like this authenticate(request, username=username, password=password)

Django is not redirecting to profile page after login. What is wrong with my code?

This is my views.py
def LoginPage(request):
username = password = ''
next = ""
if request.GET:
next = request.GET['next']
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username = username, password = password)
if user is not None:
login(request, user)
if next == "":
return HttpResponseRedirect('/Profile/')
else:
return HttpResponseRedirect(next)
context = {}
return render(request, 'login.html', context)
This is my template:
{% if next %}
<form class="" action='/Profile/' method="post">
{%else%}
<form class="" action="/Login/" method="post">
{% endif %} {% csrf_token %}
<p class="login-field-title"><strong>Username*</strong></p>
<input type="text" class="form-control col-lg-10 log-inp-field" placeholder="Enter Username" required>
<p class="login-field-title"><strong>Password*</strong></p>
<input type="password" class="form-control col-lg-10 log-inp-field" placeholder="Enter Password" required> {% for message in messages %}
<p id="messages">{{message}}</p>
{% endfor %}
<button type="submit" class="btn btn-dark btn-lg col-lg-10 log-btn">Log In</button>
</form>
I don't understand what I'm doing wrong. Some help would be very appreciated. Even after logging in with a registered user it is not redirecting me to the desired page and when i change the action, even with the un registered user it redirects me to the next page.
Add this to your settings file
LOGIN_REDIRECT_URL = 'YOUR_PROFILE_URL'

Use next parameter for login_required views

My method to redirect a url after login, work well but the code of the template is not very sexy, can I have yours please ?
my function in views.py
def connexion(request):
error = False
n=request.GET.get('n')
if request.method == "POST":
form = ConnexionForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user:
login(request, user)
if request.GET.get('n'):
return redirect(request.GET['n'])
else:
return redirect(accueil)
else:
error = True
else:
form = ConnexionForm()
return render(request, 'blog/connect_user.html', locals())
my template:
<h1>Se connecter</h1>
{% if error %}
<p><strong>Utilisateur inconnu ou mauvais mot de passe.</strong></p>
{% endif %}
{%if n %}
<form method="post" action="{% url 'connexion' %}?n={{ n }}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Se connecter" />
</form>
{% else %}
<form method="post" action="{% url 'connexion' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Se connecter" />
</form>
{% endif %}
my decorator:
#login_required(redirect_field_name='n')
Why not just:
<input type="hidden" name="n" value="{{ n }}">
And in the view:
n = request.REQUEST.get('n', '')
Using request.REQUEST you can get n from either using POST or GET so you can still link to a URL like /login?n=/foo/bar. You can also do POST/REDIRECT/GET without problems.

CSRF token missing or incorrect in signup

I'm trying to add a signup function to my website, this is what I have done so far...
added {% csrf_token %} in home.html
use render instead of rendor_to_response
added the middleware 'django.middleware.csrf.CsrfViewMiddleware'
home.html:
<div class="panel right">
<p>
<form action="/signup" method="post">
{% csrf_token %}
{% for field in user_form %}
{{ field }}
{% endfor %}
<input type="submit" value="Create Account">
</form>
</p>
</div>
Signup method in views.py
def signup(request):
user_form = UserCreateForm(data=request.POST)
if request.method == 'POST':
if user_form.is_valid():
username = user_form.clean_username()
password = user_form.clean_password2()
user_form.save()
user = authenticate(username=username, password=password)
login(request, user)
return render(request,'blog.html')
else:
return render(request,'index.html')
return redirect('/')
What's wrong with my code?