I suppose that the problem of this error is hidden in template. Here is my form:
<form class="form-horizontal loginFrm" action="/login/" method="post">
{% csrf_token %}
<div class="control-group">
<input type="text" id="inputEmail" placeholder="Email" name = "username">
</div>
<div class="control-group">
<input type="password" id="inputPassword" placeholder="Password" name = "password">
</div>
<div class="control-group">
<label class="checkbox">
<input type="checkbox"> Remember me
</label>
</div>
<input type="submit" class="btn btn-success" value="Sign in">
</form>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
And my login view:
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)
args['username'] = username
return HttpResponseRedirect('/', args, context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/', args, context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/',args,context_instance=RequestContext(request))
In my last project, it worked correctly. But here is this error.
View the html source on your page with the rendered login form and confirm that you have a hidden field with the csrf token.
Something like this:
<input type='hidden' name='csrfmiddlewaretoken' value='NzYXoXbN9beogdB6gf22rNXkTNQd6Jri' />
It's possible that the view you have is not passing the context_instance. It depends which method you are using to render the view in the first place.
You could use:
return render_to_response('my_template.html',
context_instance=RequestContext(request))
Or the easier render() which will automatically use RequestContext
return render(request, 'my_template.html')
as a case you can use ensure_csrf_cookie view decorator.
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.
<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.
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 a problem with updating an existing user object in my database. When I update and change the user object it saves and everything is looking ok but when I change the user and I want to login this user does not authenticate. Here is my code:
def profile_edit(request):
user = request.user
profile = request.user.profile
context = {
'user': user
}
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
email = request.POST.get('email')
user.profile.address = request.POST.get('address')
user.profile.phone = request.POST.get('phone')
user.set_password('password')
user.username = username
user.save()
user.profile.save()
authenticate(user)
context = {
'profile': profile
}
return render(request, 'helpdesk/profile.html', context)
return render(request, 'helpdesk/profile_edit.html', context)
and login view:
def login_view(request):
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)
profile = request.user.profile
context = {
'profile': profile
}
return render(request, 'helpdesk/user_desk.html', context)
else:
context = {
'username': username,
'error': 'user not find!'
}
else:
context = {}
return render(request, 'helpdesk/login.html', context)
When updating the password you are actually setting the string 'password' as password and not the submitted password. Change user.set_password('password') to user.set_password(password) to correct this.
<form action="" style="font-size: 2cm" method="post">
{% csrf_token %}
<div class="row" style="margin: 7px">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="username" id="first_name" class="form-control input-sm" placeholder="username:{{ request.user.username }}">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="address" id="last_name" class="form-control input-sm" placeholder="address:{{ request.user.address }}">
</div>
</div>
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-sm" placeholder="email: {{ request.user.email }}">
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-sm" placeholder="Password">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="phone" id="password_confirmation" class="form-control input-sm" placeholder="phone:{{ request.user.phone }}">
</div>
</div>
</div>
<input type="submit" value="EDIT" class="btn btn-info btn-block" style="background-color: #0d0d0d; border-color: #0d0d0d">
</form>
<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')