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
Related
RuntimeError at /signup
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/signup/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
I got this problem while using forms. Please help
I have used bootstrap for styling
<form action="/signup/" method = "post" >
{% csrf_token %}
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">#</span>
<input type="text" class="form-control" placeholder="Username" name = "username" aria-label="Username" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Firstname" name="fname" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Lastname" name="lname" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Recipient's email" name="email" aria-describedby="basic-addon2">
<span class="input-group-text" id="basic-addon2">#gmail.com</span>
</div>
<div class="input-group mb-3">
<input type="password" placeholder="password" name = "password" class="form-control">
</div>
<div class="input-group mb-3">
<input type="password" placeholder="confirm password" name = "con_password" class="form-control">
</div>
<div class="input-group mb-3">
<button type="submit" class="btn btn-primary">Signup</buttpn>
</div>
</form>
</div>
Views.py
def signup(request):
if (request.method == "POST"):
username = request.POST.get("username")
fname = request.POST.get("fname")
lname = request.POST.get("lname")
email = request.POST.get("email")
password = request.POST.get("password")
con_password = request.POST.get("con_password")
User.objects.create_user(username=username, first_name=fname, last_name=lname, email=email, password=password)
User.save()
messages.success(request, "Account created successfully")
return redirect("login")
Should Redirect to login Page
Either add APPEND_SLASH=False in settings.py. Or change form action="/signup/" to form action="/signup"
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.
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>
After POST method signup page always redirects to same page without printing any message or redirecting to homepage or login page but I am tracing it in every steps by printing something to check how it is working. But I can signup a new user using python shell.
Terminal is giving me only this:
[28/Nov/2019 15:36:26] "GET / HTTP/1.1" 200 2574
[28/Nov/2019 15:36:46] "POST / HTTP/1.1" 200 2574
def signup(request):
if request.user.is_authenticated:
return render(request,'/',{})
form = UserForm(request.POST or None)
if request.method == 'POST':
print("step 2")
if form.is_valid():
user = form.save(commit= False)
username= form.cleaned_data['username']
password= form.cleaned_data['password']
user.set_password(password)
user.save()
authenticate(username= username, password= password)
Profile.objects.create(
user= user,
full_name=form.cleaned_data['full_name'],
codeforces_id= form.cleaned_data['codeforces_id'],
Uva_Id = form.cleaned_data['Uva_Id'],
points = 0,
department= form.cleaned_data['department']
)
if user is not None:
if user.is_active:
login(request,user)
return redirect('/')
return render(request, 'signup.html',{'msg':'Invalid'})
else:
error = form.errors
print("error step")
return render(request, 'signup.html',{'msg':error})
else:
return render(request,'signup.html',{})
forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget= forms.PasswordInput)
full_name = forms.CharField(required= True)
codeforces_id = forms.CharField(required= True)
Uva_Id = forms.CharField(required= True)
department = forms.CharField(required= True)
class Meta:
model = User
fields=('username','email','password','full_name','codeforces_id','Uva_Id','department')
signup.html:
<body>
<div class="wrapper">
<div class="inner" style="width: 500px;">
{% block content %}
<form action="" method="post" style="padding-top: 40px; padding-bottom: 50px">
{% csrf_token %}
<h3 style="margin-bottom: 20px">New Account?</h3>
<div class="form-group">
<label for="username" class="control-label">Username</label>
<input type="text" class="form-control" name="username" placeholder="username">
</div>
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="text" class="form-control" name="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password" class="control-label">password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group">
<label for="full_name" class="control-label">fullname</label>
<input type="text" class="form-control" name="full_name" placeholder="Full Name">
</div>
<div class="form-group">
<label for="codeforces_id" class="control-label">codeforces_id</label>
<input type="text" class="form-control" name="codeforces_id" placeholder="codeforces_id">
</div>
<div class="form-group">
<label for="Uva_Id" class="control-label">Uva_Id</label>
<input type="text" class="form-control" name="Uva_Id" placeholder="uva_id">
</div>
<div class="form-group">
<label for="department" class="control-label">department</label>
<input type="text" class="form-control" name="department" placeholder="department">
</div>
<button type="submit" style="margin-top:20px">
<span>Register</span>
</button>
<p style="color: red">{{ msg }}</p>
<a style="float: right" href="/login">Already have an account</a>
</form>
{% endblock %}
</div>
</div>
</body>
Updated:
url.py
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'^login/$',views.Login,name= 'Login'),
url(r'^signup/$',views.signup,name='signup'),
url(r'^logout/$',views.Logout,name='logout'),
You havent included the url that the form should hit on POST
[...]
<form action="{% url 'name-of-the-url-that-leads-to-your-view' %}" method="post" style
[...]