Login through dropdown menu in Django - django

I have struggle with django's login. So i want user to login through my dropdown menu, but my LoginForm doesnt show up. I dunno what to do
forms.py
class LoginForm(forms.Form):
username = forms.CharField(label=(u'Username'),widget = forms.TextInput(attrs = {'placeholder': 'Username'}))
password = forms.CharField(max_length=16, label=(u'Password'),
widget = forms.PasswordInput(attrs = {'placeholder': 'Password (min 8 chrct)'}, render_value = False),
validators=[MinLengthValidator(8, message = 'Password must be at least 8 characters')])
views.py
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
tutor = authenticate(username=username, password=password)
if tutor is not None:
login(request, tutor)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
else:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
else:
form = LoginForm()
context = {'form': form}
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
navbar.html
<a class="dropdown-toggle" href="#" data-toggle="dropdown">Login <strong class="caret"></strong></a>
<div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;">
<form action="" method="POST">
{% csrf_token %}
{% if form.errors %}
{{ form.errors}}
{% endif %}
{{form}}
<input class="btn btn-primary" type="submit" value="Login" />
</form>
</div>

It looks like your issue is not with Django but with your bootstrap drop down.
Wrap your drop down html in a <div class="dropdown">.
<div class="dropdown">
<a class="dropdown-toggle" href="#" data-toggle="dropdown">Login <strong class="caret"></strong></a>
<div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;">
<form action="" method="POST">
{% csrf_token %}
{% if form.errors %}
{{ form.errors }}
{% endif %}
{{ form }}
<input class="btn btn-primary" type="submit" value="Login"/>
</form>
</div>
</div>

Related

Unable to login using Django

This is my login view
def login_request(request):
if request.method == 'POST':
username = request.POST.get['username']
password = request.POST.get['password']
user = authenticate(username = username, password = password)
if user is not None:
form = login(request, user)
messages.success(request, f' welcome {username} !!')
return redirect('index')
else:
messages.info(request, f'Unable to Login now')
form = AuthenticationForm()
context = {'form':form}
return render(request, "BizzyCardApp/log-in.html", context)
and this is the log-in.html file
{% extends "BizzyCardApp/base.html" %}
{% block content %}
{% load crispy_forms_tags %}
<br>
<br>
<br>
<br>
<br>
<div class="container center oswald" id="grad" style="border-radius: 10%; width: 300px;">
<br>
<form>
<table class="table table-borderless table-responsive container">
<tbody>
<tr>
<div class="mb-3 mt-3">
<form method="POST">
{% csrf_token %}
{% for field in form %}
<div>
<p>{{ field.label }}: <br> {{ field }}</p>
{% for error in field.errors %}
<small style="color: red">{{ error }}</small>
{% endfor %}
</div>
{% endfor %}
</form>
</div>
</tr>
<tr>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-light center text-center">Submit</button>
</div>
</tr>
</tbody>
</table>
</form>
<div class="text-center">
<a href="/sign-up/" class="link-dark">
Don't have an account? Sign Up
</a>
</div>
</div>
{% endblock %}
Once I hit the Submit button, it's supposed to redirect me to the index page but all that happens is that the GET request is done but there is no response from the backend to redirect. It just stays on the same page and the URL changes to
http://127.0.0.1:8000/login/?csrfmiddlewaretoken=0rkrC5wOe8LDQc9x0s0Zdag45PXRZixJAYaQns3dod58QhUL6OdmTEvZMYdRNTfq&username=tushar&password=abcd123*
Try this login view:
def login_request(request):
if request.method == 'GET':
if request.user.is_authenticated:
return redirect('/index/')
if request.method=='GET':
form = loginForm(request.POST)
if form.is_valid():
user=authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password'])
if user:
print('user',user)
login(request,user)
return redirect('/index/')
else:
print('Not authenticated')
elif request.method=='GET':
if request.user.is_authenticated:
return redirect('/index/')
form=loginForm()
return render(request,'users/login.html',{'form':form})
In forms.py:
Add this:
class CustomAuthenticationForm(AuthenticationForm):
def confirm_login_allowed(self, user):
if not user.is_active or not user.is_validated:
raise forms.ValidationError('There was a problem with your login.', code='invalid_login')
And in login view, change AuthenticationForm to CustomAuthenticationForm. And import it in login view using below code.
from .form import CustomAuthenticationForm
Finally figured out the answer. The method for the tag wasn't given as POST.
The tag was just and not
The backend kept on getting GET requests instead and that's why the code wasn't working.
This is the Login method code I'm using now
def Login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username = username, password = password)
if user is not None:
form = auth_login(request, user)
messages.success(request, f' welcome {username} !!')
return redirect('/')
else:
messages.info(request, f'account done not exit plz sign in')
form = AuthenticationForm()
return render(request,'BizzyCardApp/log-in.html',{'form':form})

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>

MultiValueDictKeyError, when I press sign up button

<div class="modal-signin" >
<h1>Login</h1>
<button id="exit_login">X</button>
<div class="form-for-signin">
<center>
<form id="login-form" method="post">
{% csrf_token %}
<label id="username-label">Username:</label><br>
<input class='username-input-field' id={{ form.username }} <br>
<label id="password-label">Password:</label><br>
<input class="password-input-field" id={{ form.password }} <br>
<button type="submit" class="submit-btn">Log in</button>
</form>
</center>
</div>
<div class="social-links">
<div id="social">
<a class="facebookBtn smGlobalBtn" href="#"></a>
<a class="twitterBtn smGlobalBtn" href="#"></a>
</div>
<div class="dont-have-an-account">
<p>Don't have an account?<button id="sign-up-button" style="font-size: inherit; outline: none; background: none; border: none">Sign up</button></p>
</div>
</div>
</div>
<div class="modal-signup">
<center>
<form method="post">
{% csrf_token %}
<h1>Sign up</h1>
<div class="inside-the-signup-form">
<label id="first-name-label">First name:</label><br>
<input id="{{ form_signup.first_name }}" required> <br>
<label id="last-name-label">Last name:</label><br>
<input id="{{ form_signup.last_name }}"><br>
<label id="username-label">Create Username:</label><br>
<input id="{{ form_signup.username }}"><br>
<label id="email-label">Email:</label><br>
<input id="{{ form_signup.email }}"><br>
<label id="createpassword-label">Create password:</label><br>
<input id="{{ form_signup.password }}"><br>
<label id="password2-label">Confirm password:</label><br>
<input id="{{ form_signup.password2 }}"><br>
</div>
<button type="submit">Sign Up</button>
</form>
</center>
views.py
def logging_in(request):
if request.method == 'POST':
form= LoginForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user= authenticate(username=username, password=password)
if user is not None:
if form.is_valid():
login(request, user)
messages.success(request,'Logging in...')
else:
messages.error(request,'username or password is incorrect')
form= LoginForm()
else:
form = LoginForm()
return render(request, 'home.html', {'form': form})
def sign_up(request):
if request.method == 'POST':
form_signup = SignUpForm(request.POST)
if form_signup.is_valid():
password= request.POST['password']
password2= request.POST['password2']
if password != password2:
messages.error(request,'Password does not match')
form_signup= SignUpForm()
else:
form_signup.save()
else:
form_signup= SignUpForm()
else:
form_signup= SignUpForm()
return render(request, 'home.html', {'form_signup':form_signup})
I linked both of my views to the same page because I want my signup to be a modal (popup). If you have any suggestions on how I should change my code so when i press submit on my signup form, I don't get MultiValueDictKeyError at /'username'
Both forms contain basically what you expect. The signup has first_name, last_name, email, username, etc...
Please don't forget that I am creating a modal so the log in or sign up form should not affect the url.
Best way to avoid this, you can change
username = request.POST['username']
password = request.POST['password']
to this:
username = request.POST.get('username')
password = request.POST.get('password')

Django: custom login does not show validation errors upon unsuccessful login attempt

the code is for some reason not showing the validation errors (that are shown in the forms.py) when a person unsuccessfully logs in. It just displays the empty template. I believe the template is getting overwritten but I am not sure whereabouts in my code is the problem:
views.py
def log_in(request):
form = LogInForm(request.POST or None)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('menu')
return HttpResponseRedirect("/login")
else:
return render(request, 'login.html', {'form': form})
login.html
{% extends 'html/base.html' %}
{% load bootstrap %}
{% load static %}
{% block add_head %}
<link rel="stylesheet" href="{% static 'css/login.css' %}">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link rel="stylesheet" href="{% static 'css/menu.css' %}">
{% endblock %}
{% block logout %}
<a href="{% url 'index' %}" class="button" type="button"
style="vertical-align:middle; background-color: red; width: 7%;"><span>Home</span></a>
{% endblock %}
{% block content %}
<div class="container">
<div class="row" style="margin-top:20px; text-align: center; font-size: large">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="POST" enctype="multipart/form-data">
<hr class="colorgraph" style="margin-top: 0">
{{ form|bootstrap }}
<hr class="colorgraph">
{% csrf_token %}
<div style="text-align: center;">
<input type="submit" class="btn btn-lg btn-primary inline-block"
style="width: 30%; background: purple; border: purple;" value="Log in"/>
<a href="{% url 'signup' %}" class="btn btn-lg btn-primary inline-block"
style="width: 30%; background: purple; border: purple;" type="button"><span>Sign-up</span></a>
</div>
</form>
</div>
</div>
</div>
<link rel="script" href="{% static 'js/login.js' %}">
{% endblock %}
{% block user_message %}
{% endblock %}
forms.py
class LogInForm(forms.ModelForm):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'password')
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
user = authenticate(username, password)
if not user or not user.is_active:
raise forms.ValidationError("Sorry, that login was invalid. Please try again.")
return self.cleaned_data
urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^signup/$', views.sign_up, name='signup'),
url(r'^login/$', views.log_in, name='login'),
url(r'^activate/$', views.activate_user_account, name='activate_user_account'),
]
thanks very much. it seems like it would be a really small thing to solve, as it all works how it should it just does not show errors.
You have to call form.is_valid()
def log_in(request):
form = LogInForm(request.POST or None)
if request.method == 'POST':
if not form.is_valid(): # Here
return render(request, 'login.html', {'form': form})
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('menu')
return HttpResponseRedirect("/login")
else:
return render(request, 'login.html', {'form': form})

django: form.is_valid always giving error

i am working on login page but my form always gives me error, please find my code below, please see view.py it response always go to else statment of "if form.is_valid():" condition. please help
here you can see form.py
from django.contrib.auth.models import User
from django import forms
class LoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password']
this is my view.py
def login_view(request):
template_name = 'user/login.html'
form_class = LoginForm
if request.method == "POST":
form = form_class(data=request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
try:
login(request, user)
return redirect('user:profile')
except:
form = form_class(None)
return render(request, template_name, {'form': form, 'custom_error': 'Error'})
else:
return HttpResponse("<h1>Data is invalid</h1>")
else:
if request.user.is_authenticated():
return redirect('user:profile')
else:
form = form_class(None)
return render(request, template_name, {'form': form,})
user/login.html
{% block body %}
<div class="section">
<div class="container">
<div class="row">
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-md-5">
<img src="{% static 'user/images/favicon.png' %}" class="img-responsive">
</div>
<div class="col-md-6">
{% include 'user/form-template.html' %}
<div class="col-sm-offset-2 col-sm-10" align="right">
<button type="submit" class="btn btn-default" autofocus>Sign In</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
and finally this is my form-template.html file
{% for field in form %}
<div class="col-md-8">
<div class="col-md-4">
<label>{{ field.label_tag }} </label>
</div>
<div class="col-md-4">
{{ field }}
<div>
<span>{{ field.errors }}</span>
</div>
<div>
<span class="text-danger small">{{ custom_error }}</span>
</div>
</div>
</div>
{% endfor %}
If you are using ModelForm, you are going to operate on django model objects, creating, updating, etc. If you are only trying to login, use Form instead.
Thanks its solved, I just Changed My Form no it looks like this.
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
now i am not using built-in form and i also changed ModelForm to Form.