<form action="login" method="post" >
{% csrf_token %}
<div class="form-group mb-3">
<label class="label" for="name">username</label>
<input type="text" id="username" class="form-control" required>
</div>
<div class="form-group mb-3">
<label class="label" for="password">password</label>
<input type="password" id="password" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" action="login">
</div>
<div class="form-group d-md-flex">
<div class="w-50 text-left">
<label class="checkbox-wrap checkbox-primary mb-0">Remember Me
<input type="checkbox" checked>
<span class="checkmark"></span>
</label>
</div>
<div class="w-50 text-md-right">
Forgot Password
</div>
This is the form.
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:
login(request, user)
return redirect("dashboard")
else:
messages.info(request, "User doesn't exist. Contact the teacher!")
return redirect("index")
else:
return render(request, "login.html")
This is the views function.
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
from django.contrib.auth import authenticate, login
Those are the imports.
But this doesn't redirect user who has already registered, to the page specified. Not a problem of urls or the csrf_token. I think the problem is in the sending data part because the else function triggers and shows the massege user doesn't exist..... Please help.
Related
I'm making a sign up page.
html
{{message}}
<form action="{% url 'signup' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input class="form-control" autofocus type="text" name="username" placeholder="Username">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="Email Address">
</div>
<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="Password">
</div>
<div class="form-group">
<input class="form-control" type="password" name="confirmation" placeholder="Confirm Password">
</div>
<input class="btn btn-primary" type="submit" value="Register">
</form>
django
def signup(request):
if request.method == 'POST':
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
confirmation = request.POST['confirmation']
if password != confirmation:
return render(request, 'lms/signup.html', {
'message': 'Passwords must match.'
})
else:
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, 'lms/signup.html', {
'message': 'Username already taken.'
})
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'lms/signup.html')
When I submit the form, I get this error:
OperationalError at /signup
no such table: lms_user
I've already done the migrations command. I also deleted tried deleting migrations and pycache folder's content and db.sqlite3 file and did the migrations again but that didn't help either.
So, I've tried a couple of times to register and back to login. Always failed to log in except for superuser or admin. Already checked in Django admin that the user that I have registered already there.
There is no error message in the terminal when login or register a user. Except for the error message that I've created in views.py if log in unsuccessful.
So, let's take a look into my code. First views.py
from django.contrib.auth import authenticate, login, logout
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
# Check if authenticate successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
context = {
"message": "Invalid username and/or password"
}
return render(request, "page/login.html", context)
else:
return render(request, "page/login.html")
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches with password confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
context = {
"message": "Both password must match"
}
return render(request, "page/register.html", context)
# Attempt to create new user
try:
user = User.objects.create_user(username)
user.save()
except IntegrityError:
context = {
"message": "Username already exist"
}
return render(request, "page/register.html", context)
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "page/register.html")
And below is the template both for log in and register.
<!-- Logintemplate -->
<div class="login-register">
<div class="head">
Log in to Explore
</div>
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" id="username" name="username" placeholder="Username"">
<label for="username">Username</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
<label for="password">Password</label>
</div>
<div class="d-grid gap-2">
<input class="btn btn-outline-success" type="submit" value="Login">
</div>
<div id="log-reg">
Sign Up
</div>
</form>
{% if message %}
<div class="alert alert-danger mt-4" role="alert">
{{ message }}
</div>
{% endif %}
</div>
<!-- Register template -->
<div class="login-register">
<div class="head">
Create your account
</div>
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" autofocus type="text" name="username" id="username" placeholder="Username">
<label for="username">Username</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control" name="email" id="email" placeholder="name#example.com">
<label for="email">Email address</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
<label for="password">Password</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="confirmation" name="confirmation" placeholder="Confirm Password">
<label for="confirmation">Password Confirmation</label>
</div>
<div class="d-grid gap-2">
<input class="btn btn-outline-success" type="submit" value="Register">
</div>
<div id="log-reg">
Already have an account? Log In here.
</div>
</form>
{% if message %}
<div class="alert alert-danger mt-4" role="alert">
{{ message }}
</div>
{% endif %}
</div>
Is there something I missed or action that I need to perform?
You create the user as follows:
user = User.objects.create_user(username)
This creates a user without a password which means your user would not be able to login. pass the username and password both to the create_user method:
user = User.objects.create_user(username=username, password=password)
Note: Use a form class to make forms in Django to perform validation and cleaning. For making a user use the
UserCreationForm
I have created a user and given him all the required data, but I cannot log into the page, I sure the email and password correct , but it gives me error in the information entered.
template:
<form action="" method="post" class="border rounded overflow-hidden p-5">
{% csrf_token %}
<h4 class="text-center py-3 title">Login </h4>
{% for message in messages %}
<div class="btn btn-sm btn-dark col-6" role="alert">
<h3 class="text-center"> {{ message }}</h3>
</div>
{% endfor %}
<div class="row">
<div class="form-group col-md-12 text-left px-0">
<label for="email">Email</label>
<input class="border rounded-2 p-3 bg-input " type="email" name="email" id="email" placeholder="Email ">
</div>
<div class="form-group col-md-12 text-left px-0">
<label for="password">Password </label>
<input class="border rounded-2 p-3 bg-input " type="password" class="form-control" id="password" name="password">
</div>
<button class="btn btn-sm btn-dark col-12 rounded-2 my-4 p-3" type="submit">Login </button>
</div>
</form>
my view:
from django.contrib.auth import authenticate,login
from django.shortcuts import render,redirect
from django.contrib.auth.models import auth,Group
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.decorators import login_required
from .decorators import uthenticated_user
from app.models import *
# Create your views here.
#uthenticated_user
def login(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)
return redirect('user_home')
else:
messages.error(request,'There was a problem logging in. Check your email and password or create an account')
return redirect('login')
else:
return render(request,'registration/sign-in.html')
As i know, authenticate is only taking username and password. You can try to find username by email firstly and then authenticate him:
#uthenticated_user
def login(request):
if request.method=='POST':
email=request.POST['email']
password=request.POST['password']
# New code
try:
username = User.objects.get(email=email).username
except User.DoesNotExist:
username = None
user=authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect('user_home')
else:
messages.error(request,'There was a problem logging in. Check your email and password or create an account')
return redirect('login')
else:
return render(request,'registration/sign-in.html')
I am new to Django. I am creating a signup page. But I am having an unexpected MultiValueDictKeyError with Exception value fname.
views.py:
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
# Create your views here.
def signup(request):
if request.method == 'POST':
# User has and wants account now
if request.POST['password1'] == request.POST['password2']:
# Check if username already exists
try:
user = User.objects.get(username=request.POST['uname'])
return render(request, 'accounts/signup.html',{'error':'username already exist'})
# If username unoccupied
except User.DoesNotExist:
user = User.objects.create_user(fname = request.POST['fname'],lname = request.POST['lname'],email = request.POST['email'],uname = request.POST['uname'],password = request.POST['password1'])
# updating new user
auth.login(request,user)
return redirect('home')
else:
return render(request,'accounts/signup.html')
def login(request):
if request.method == 'POST':
#
user = auth.authenticate(username = request.POST['username'],password = request.POST['password'])
if user is not None:
auth.login(request,user)
return redirect('home')
else:
return render(request, 'accounts/login.html',{'error': 'username or password incorrect'})
else:
#
return render(request,'accounts/login.html')
def logout(request):
if request.method == 'POST':
auth.logout(request)
return redirect('home')
sign up page:
{% extends 'base.html'%}
{% block content %}
<div class="container-fluid" style="background-image: linear-gradient(to right, #1a1aff , #000099);padding: 10vh">
<div class="row">
<div class="col center" style="color: white;padding: 05vw">
<h1> Sign Up Now! </h1>
<br>
<h2> Become the part world's first personalized <br> Network <h2>
</div>
<div class="col-5 center container" style="color:black;padding: 02vw;background-color: white;">
<span>
<center>
<h1>Sign Up</h1>
</center>
<br>
</span>
<form action="{% url 'signup' %}" method="POST">
{% csrf_token %}
{% if error %}
<p style="color:red "> {{error}} </p>
{% endif %}
<h3>First Name</h3>
<input type="text" id="fname" name="firstname" placeholder="Your name..">
<br>
<h3>Last Name</h3>
<input type="text" id="lname" name="lastname" placeholder="Last Name">
<br>
<h3>Email</h3>
<input type="email" id="email" name="email" placeholder="Email Address">
<br>
<h3>Username</h3>
<input type="text" id="uname" name="uname" placeholder="Username">
<br>
<h3>Password</h3>
<input type="password" id="password" name="password1" placeholder="Password">
<br>
<h3>Confirm Password</h3>
<input type="password" id="password" name="password2" placeholder="Password">
<br>
<br>
<input type="submit" value="Sign Up Now">
</form>
</div>
</div>
</div>
enter code here
{% endblock %}
The field is firstname, not fname. This is why you should use Django forms rather than accessing the POST directly
Im trying to write my own django login page. Eveything is ok up to the point where I try to login and I just get redirected back to the main login view.
TEMPLATE
{% extends "bdayremind-maininput.html" %}
{% block main %}
<form class="form-horizontal" name="LoginForm" action="/login/" method="post">
{% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" value="{{username}}" placeholder="Username">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Login</button>
</div>
</div>
</form>
{% endblock %}
URLS
urlpatterns = patterns('',
url(r'^bdayremind_maininput/$', 'birthdayreminder.views.main'),
# login / logout
(r'^login/$', 'birthdayreminder.views.login_user'),
#(r'^logout/$', logout_page),
)
VIEWS
import datetime
from django.http import *
from django.shortcuts import render_to_response
from django.template import RequestContext
from birthdayreminder.models import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
def login_user(request):
username = password = ''
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('birthdayreminder.views.main')
return render_to_response('login.html',{'username': username}, context_instance=RequestContext(request))
#login_required(login_url='/login/')
def main(request):
........
Any Ideas ?
You forgot to add redirect to the desired page after login.