I have a login function, however when I try to login with a user that is not admin Django's authenticate function returns None even though the user exists in the database and the function receives the right username and password.
def login_user(request):
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
print(username, password)
user = authenticate(username=username, password=password)
print(user)
if user is not None:
login(request, user)
return redirect("/")
else:
return render(request, "orders/login.html",
{"message":"Username and password did not match."})
else:
return render(request, "orders/login.html")
login template:
{% extends "orders/layout.html" %}
{% block title %}
Login
{% endblock %}
{% block body %}
<div class="forms">
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label>Username</label>
<input class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password">
{% if message %}
<small id="emailHelp" class="form-text text-muted">{{ message }}</small>
{% endif %}
</div>
<button type="submit" class="btn button" id="button1" >Log In</button>
<a class="btn button" href="{% url 'register' %}" role="button" id="button2">Register</a>
</form>
</div>
{% endblock %}
url.py :
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("menu/<product>/", views.menu, name="menu"),
path("register", views.register, name="register"),
path("add_to_cart", views.addToCart, name="add_to_cart"),
path("cart", views.cart, name="cart"),
path("confirm", views.confirm, name="confirm"),
path("login", views.login_user, name="login"),
path("logout", views.logout_user, name="logout")
]
Try this :
def login_user(request):
if request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
print(username, password)
if username and password:
user = authenticate(username=username, password=password)
if user is not None:
If user.is_active:
login(request, user)
return redirect("/")
else:
return render(request, "orders/login.html",
{"message":"User does not exist."})
else:
return render(request, "orders/login.html",
{"message":"Username and password did not match."})
else:
return render(request, "orders/login.html")
Related
Good day,
I am making a Django application,
I want to call my data that the user signs up with and to display the information they submitted as:
Name
Email
Then I want to be able to change that data and then I want to save it, and reload back into the dashboard, but when I am updating my 'update_profile.html' the info is not updating, I can; add form data and change it
What am I doing wrong?
My code below:
views.py
from django.shortcuts import render, redirect, HttpResponse
from django.contrib import messages, auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from contacts.models import Contact
def register(request):
if request.method == 'POST':
# Get form values
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password2 = request.POST['password2']
# Check if passwords match
if password == password2:
# Check username
if User.objects.filter(username=username).exists():
messages.error(request, 'That username is taken')
return redirect('register')
else:
if User.objects.filter(email=email).exists():
messages.error(request, 'That email is being used')
return redirect('register')
else:
# Looks good
user = User.objects.create_user(
username=username, password=password, email=email, first_name=first_name, last_name=last_name) # noqa
# Login after register
auth.login(request, user)
messages.success(request, 'You are now logged in')
return redirect('index')
# user.save()
# messages.success(
# request, 'You are now registered and can log in')
# return redirect('login')
else:
messages.error(request, 'Passwords do not match')
return redirect('register')
else:
return render(request, 'accounts/register.html')
def login(request):
if request.method == '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)
messages.success(request, 'You are now logged in')
return redirect('dashboard')
else:
messages.error(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'accounts/login.html')
def logout(request):
if request.method == 'POST':
auth.logout(request)
messages.success(request, 'You are now logged out')
return redirect('index')
#login_required(login_url='login')
def dashboard(request):
user_contacts = Contact.objects.order_by(
'-contact_date').filter(user_id=request.user.id)
context = {
'contacts': user_contacts
}
return render(request, 'accounts/dashboard.html', context)
#login_required(login_url='login')
def edit_profile(request, pk):
user = User.objects.get(id=pk)
if request.method == 'POST':
...
user.name = request.GET['name']
user.email_address = request.GET['email_address']
user.save()
return redirect('dashboard')
context = {
'user': user
}
return render(request, 'accounts/dashboard.html', context)
#login_required(login_url='login')
def delete_profile(request, pk):
user = User.objects.get(id=pk)
if request.method == 'POST':
...
user.name = request.GET['name']
user.email_address = request.GET['email_address']
user.delete()
return redirect('index')
context = {
'user': user
}
return render(request, 'index.html', context)
Then my urls
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('register', views.register, name='register'),
path('login', views.login, name='login'),
path('logout', views.logout, name='logout'),
path('dashboard', views.dashboard, name='dashboard'),
path('edit_profile/<int:pk>/', views.edit_profile, name='edit_profile'),
]
Lastly My edit_profile.html
{% extends 'base.html' %}
{% block title %} | Edit Profile {% endblock %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">User Dashboard</h1>
<p class="lead">Manage your BT Real Estate account</p>
</div>
</div>
</div>
</section>
<!-- Breadcrumb -->
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> Dashboard</li>
</ol>
</nav>
</div>
</section>
{% comment %} Alerts {% endcomment %}
{% include 'partials/__alerts.html' %}
<section id="dashboard" class="py-4">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Welcome {{ user.first_name }}
<a class="btn btn-info" href="{% url 'dashboard' %}">
Save Profile
</a>
<a class="btn btn-da nger" href="{% url 'dashboard' %}">
Del;ete Profile
</a>
</h2>
<h3>Account Details: </h3>
<form action="{% url 'contact' %}" method="POST">
{% csrf_token %}
{% if user.is_authenticated %}
<input type="hidden" name="user_id" value="{{ user.id }}">
{% else %}
<input type="hidden" name="user_id" value="0">
{% endif %}
<input type="hidden" name="realtor_email" value="{{ listing.realtor.email }}">
<input type="hidden" name="listing_id" value="{{ listing.id }}">
<div class="form-group">
<label for="property_name" class="col-form-label">Property:</label>
<input type="text" name="listing" class="form-control" value="{{ listing.title }}" >
</div>
<div class="form-group">
<label for="name" class="col-form-label">Name:</label>
<input type="text" name="name" class="form-control" {% if user.is_authenticated %} value="{{ user.first_name }} {{ user.last_name }}" {% endif %} required>
</div>
<div class="form-group">
<label for="email" class="col-form-label">Email:</label>
<input type="email" name="email" class="form-control" {% if user.is_authenticated %} value="{{ user.email }}" {% endif %} required>
</div>
<div class="form-group">
<label for="phone" class="col-form-label">Phone:</label>
<input type="phone" name="phone" class="form-control" {% if user.is_authenticated %} value="{{ user.phone }}" {% endif %} >
</div>
<input type="submit" value="Send" class="btn btn-block btn-secondary">
</form>
</div>
</div>
</div>
</section>
{% endblock %}
PLEASE HELP!
this is a shopping website my login and registration form is not working it is showing that no reverse path found error.
this is my navbar template
<div class="container py-5">
<p class="text-center">If you already have an account, <a href="{% url
'sweet:register_request' %}">login</a> instead.</p>
</div>
<div class="container py-5">
<p class="text-center">Don't have an account? Create an account.
</p>
</div>
login.html
this is my login template
{% extends "base.html" %}
{% load static %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{ login_form }}
<button class="btn btn-primary" type="submit">Login</button>
</form>
{% endblock %}
home.html
this is my registration template
{% extends "base.html" %}
{% load static %}
{% block content %}
<form method="POST">
<button class="btn btn-primary" type="submit">Register</button>
{% csrf_token %}
{{register_form}}
</form>
{% endblock %}
views.py
register_request is function defined to register the form and login_request is to login into my website
def register_request(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
messages.success(request, "Registration successful.")
return redirect('login_request')
messages.error(request, "Unsuccessful registration. Invalid information.")
form = NewUserForm()
return render(request,"home.html",{"register_form": form})
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, "You are now logged in as {username}.")
return redirect("base.html")
else:
messages.error(request, "Invalid username or password.")
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request, 'login.html',{"login_form": form})
urls.py
from django.contrib.auth.views import LogoutView, LoginView
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
app_name="sweet"
urlpatterns = [
path('',views.allProdCat,name='allProdCat'),
path('<slug:c_slug>/',views.allProdCat,name='products_by_category'),
path('<slug:c_slug>/<slug:prod_slug>/', views.ProductDetail, name='ProdCatDetail'),
path('register/', views.register_request, name="register"),
path("login/", views.login_request, name="login"),
]
forms.py
the form is for registration and login
from django import forms
from django.contrib.auth.models import User
from . import models
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
this are all my code please help
You are trying to get address of views.register_request in {% url 'sweet:register_request' %} but the name of url path you have chosen is different. You can do one of two options, in both you need to change name.
Option 1:
# from
path('register/', views.register_request, name="register"),
# to
path('register/', views.register_request, name="register_request"),
Option 2:
# from
{% url 'sweet:register_request' %}
# to
{% url 'sweet:register' %}
instead of this:
<div class="container py-5">
<p class="text-center">If you already have an account, <a href="{% url
'sweet:register_request' %}">login</a> instead.</p>
</div>
<div class="container py-5">
<p class="text-center">Don't have an account? Create an account.
</p>
</div>
Do this:
<div class="container py-5">
<p class="text-center">If you already have an account, <a href="{% url
'sweet:register' %}">login</a> instead.</p>
</div>
<div class="container py-5">
<p class="text-center">Don't have an account? Create an account.
</p>
</div>
When trying to create a simple web page with login and sign up i ran into the issue of django not recognzing the created user. In views.py i created a simple message that displays "Incorrect password or email" if user does not exist. I created a user and made sure that the password was correct when i inputed it into the login form however it still gave me the message of "Incorrect password or email". Instead of redirecting to home like a created user should it errored and i could not figure out why it is not accepting the password/email in the form.
views.py
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.models import User
def home(request):
return render(request, 'home.html')
def signup(request):
if request.method == "POST":
email = request.POST['email']
password = request.POST['password']
myuser = User(email=email)
myuser.set_password(password)
myuser.save()
messages.success(request, "Your account has been successfully created ")
return redirect('signin')
return render(request, 'signup.html')
def signin(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)
email = user.email
messages.success(request, "Successfully Logged In")
return redirect ('home')
else:
messages.info(request, "Email or Password is Incorrect")
return render(request, 'signin.html')
return render(request, 'signin.html')
def signout(request):
pass
urls.py
from django.urls import path
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('', views.home, name = "home"),
path('signin', views.signin, name = "signin"),
path('signup', views.signup, name = "signup"),
]
urlpatterns += staticfiles_urlpatterns()
signup.html
<h1>Sign up</h1>
<form action = "/signup" method = "POST">
{% csrf_token %}
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name = "email" aria-describedby="emailHelp" placeholder = "example#example.com">
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name = "password">
</div>
<button type="submit" class="btn btn-primary">Sign up</button>
</form>
signin.html (login page)
<h1>Login</h1>
{%if messages%}
{%for message in messages%}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Hey,</strong> {{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
<form action = "/signin" method = "POST">
{% csrf_token %}
<div class="row mb-3">
<label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name = "email">
</div>
</div>
<div class="row mb-3">
<label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id = "password" name = "password">
</div>
<div class="col-sm-10">
</div>
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
What is the status of your user. An inactive user is one that has its is_active field set to False. The default backend ModelBackend and RemoteUserBackend prohibits the inactive users from authenticating. You didn't specify user status. So please check the user status also.
You can improve this part as following:
myuser = User(email=email, is_active=True)
myuser.set_password(password)
myuser.save()
To set password you have to use set_password function.
What I am trying to do:
I want to click a link on my page and then be redirected to another of my pages.
login.html:
{% block body %}
<h1>Login</h1>
{% if message %}
<div>
{{ message }}
</div>
{% endif %}
<form action="{% url 'login' %}" method="post">
{% csrf_token %}
<input name="username" type="text" />
<input name="password" type="password" />
<input type="submit" value="Login" />
</form>
<a class="btn btn-primary" href="{% url 'new_user' %}">New user</a>
{% endblock %}
new_user.html:
{% block body %}
<h1>New user</h1>
{% if message %}
<div>
{{ message }}
</div>
{% endif %}
<form action="{% url 'new_user' %}" method="post">
{% csrf_token %}
<input name="username" type="text" />
<input name="password" type="password" />
<input name="email" type="email" />
<input type="submit" value="Login" />
</form>
{% endblock %}
urls.py in main app:
urlpatterns = [
path("", include("orders.urls")),
path("new_user/", include("users.urls")),
path("login/", include("users.urls")),
path("admin/", admin.site.urls),
]
urls.py in users:
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("new_user", views.new_user_view, name="new_user")
]
views.py:
def index(request):
if not request.user.is_authenticated:
return render(request, "users/login.html", {"message": None})
context = {
"user": request.user
}
return render(request, "users/user.html", context)
def login_view(request):
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "users/login.html", {"message": "Invalid credentials."})
def new_user_view(request):
username = request.POST["username"]
password = request.POST["password"]
user = User.objects.create_user(username=username, password=password)
if user is not None:
user.save()
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "users/new_user.html", {"message": "Invalid credentials."})
Behavior:
What happens is I go to localhost:8000/login press the link for a new user, my browser redirects me to localhost:8000/new_user but is still rendering login.html and not new_user.html
What am I missing?
Change this
urlpatterns = [
path("", include("orders.urls")),
path("new_user/", include("users.urls")),
path("login/", include("users.urls")),
path("admin/", admin.site.urls),
]
to this
urlpatterns = [
path("", include("orders.urls")),
path("", include("users.urls")),
path("admin/", admin.site.urls),
]
All URLs from users will be included.
path("new_user/", include("users.urls")) would result in additional prefix new_user for all the urls from users. In this case localhost:8000/new_user matches index page from users app. You can try accessing localhost:8000/new_user/new_user with current configuration - it will render the page you're expecting.
Here is my code. Everything is working fine but when I tried to log in and hit on login button nothing happens. My login page didn't redirect me on any page.
Login page code:
{% extends 'authenticate/base.html' %}
{% block content%}
<h1 class="text-center">Login </h1>
<div class="col-md-6 offset-md-3"
<form method="POST">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter UserName"
name="username">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password"
name="password">
</div>
<button type="submit" class="btn btn-secondary">Login</button>
</form>
</div>
{% endblock %}`
Views.py page code:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
def home(request):
return render(request, 'authenticate/home.html',{})
def login_user(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('home')
else:
return redirect('login')
else:
return render(request, 'authenticate/login.html', {})
Base.py page code:
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="{%url 'login'%}">Login</a>
</li>
</ul>
</div>
def login_user(request):
form = LoginForm(request.POST)
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('home')
return render(request, 'authenticate/login.html', {'form':form})