So this is my login page, and I have a login button that logins the user. However, I wish to add a "Home" button that when pressed, would redirect the user to the index.html page. However, I'm unsure of how to approach this.
In my app.py flask file:
#app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
return redirect(url_for('dashboard'))
return '<h1>Invalid username or password</h1>'
elif request.form['home'] == 'Home':
print("Home pressed")
return render_template('index.html')
#return '<h1>' + form.username.data + ' ' + form.password.data + '</h1>'
return render_template('login.html', form=form)
In my login.html:
{% block content %}
<div class="container">
<form class="form-signin" method="POST" action="/login">
<h2 class="form-signin-heading">Please sign in</h2>
{{ form.hidden_tag() }}
{{ wtf.form_field(form.username) }}
{{ wtf.form_field(form.password) }}
{{ wtf.form_field(form.remember) }}
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<input type="submit" name="home" value="Home">
</form>
</div> <!-- /container -->
{% endblock %}
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!
I am creating a login form using wtforms, but the login form doesn't work the first time it is submitted. When you submit it for the second time, form.validate_on_submit() does return true.
Here is my login view:
#app.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('admin'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
redirect(url_for('admin'))
return render_template('login.html', form=form)
And here is my form html:
<form method="POST">
{{ form.hidden_tag() }}
<div class="field">
<div class="control">
{{ form.password(class="input is-large", placeholder="Your Password") }}
</div>
</div>
{{ form.submit(class="button is-block is-success is-large is-fullwidth") }}
</form>
I just fixed the bug, in my code I accidentally typed redirect(url_for('admin')) instead of return redirect(url_for('admin')).
I have problem with form validation in Flask. In login.html I have:
{% extends "base.html" %}
{% block content %}
<center>Sign In</center>
<form action="/login" method="post" >
<div class="login">
<input type="text" placeholder="Username" id="username" name="username">
<input type="password" placeholder="password" id="password" name="password">
<input type="submit" value="Sign In">
</div>
<div class="shadow"></div>
</form>
{% endblock %}
In routes.py I have:
#app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
if request.method == 'POST'and form.validate():
if(request.form["username"] is None or request.form["password"] is None):
flash("fill inputs")
else:
user = User.query.filter_by(username=request.form["username"]).first()
if user is None or not user.check_password(request.form["password"]):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user)
userCookie = request.form['username']
resp = make_response(render_template('index.html'))
resp.set_cookie('user', userCookie)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('index')
return resp
return redirect(next_page)
return render_template('login.html', title='Sign In')
Unfortunately, after clicking to log in, nothing happens even if I write correct username and password. Before I was using WTForms and everything worked well, but I couldnt add css to modify form and after changing it, the validation dosnt work well. Can somebody help me with this problem?
I want the user to be redirected to the last page after the signup form but it keeps redirecting to the homepage. I also have a login page that does redirection to the last page successfully and I'm trying to do the same with the signup. But as soon as I click the submit button after filling out the form, it just redirects to the index page
Here is the signup link
<li>Sign Up</li>
signup.html
<h1> SIGN UP </h1>
{% if user.is_authenticated and not user.is_superuser %}
<h3>Hi {{ user.first_name }}. Thanks for loggin in!</h3>
{% else %}
<form action="" method="post" id="user_uploader" enctype="multipart/form-data"> {% csrf_token %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<p class="alert">By Clicking “Sign Up” below, you are agreeing to the Meddy Terms of Service and Privacy Policy</p>
<button class="btn btn-primary" type="submit" name="submit" id="ss-submit">SIGN UP</button>
</form>
{% endif %}
views.py
def signup_user(request):
d = getVariables(request,dictionary={ 'page_name': "Sign up"})
if request.method == 'POST':
form = UserCreationForm(request.POST,request.FILES)
if form.is_valid():
new_user = form.save()
new_user = authenticate(username=request.POST['username'],password=request.POST['password1'])
login(request, new_user)
return HttpResponseRedirect(reverse('index'))
else:
print form.errors
else:
form = UserCreationForm()
d.update({'form': form,'usersignup':True})
return render(request, "d1/signup.html",d )
you forgot the redirect part in views.
#....
if form.is_valid():
username = request.POST.get('username')
password = request.POST.get('password1')
new_user = form.save()
new_user = authenticate(username=username,password=password)
login(request, new_user)
# ------------------------------------
if request.GET.get('next'):
return HttpResponseRedirect(request.GET.get('next'))
# ------------------------------------
return HttpResponseRedirect(reverse('index'))
else:
print form.errors
#...
I'm making a webpage where I login and add people to an address book. Once I login and click on the "add address" button, I'm redirected back to the login page with the following url:
http://localhost:8000/xcard/login/?next=/xcard/add_address/
If I login again I can get to account page, address book, and then add_address book page without being caught in the login loop. I can logout and login and add addresses without relogin in twice. But the first time I ever login I have to do it twice. Not sure if it's a problem with the login or the add address code.
Views.py
class LoginView(View):
def get(self, request):
''' if user is authenticated '''
if request.user.is_authenticated():
return render(request, 'xcard/account.html')
else:
return render(request, 'xcard/login.html')
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
state = "The email or password is incorrect"
if user is not None:
login(request, user)
return HttpResponseRedirect('/xcard/account/')
else:
return render(request, 'xcard/login.html', {'state':state})
class AddAddressView(View):
def get(self,request):
address_form = AddressForm()
friend_form = FriendForm()
return render(request, 'xcard/add_address.html', {'friend_form':friend_form, 'address_form':address_form})
def post(self,request):
address_form = AddressForm(request.POST)
friend_form = FriendForm(request.POST)
if address_form.is_valid() and friend_form.is_valid():
new_address = address_form.save()
new_friend = friend_form.save(commit=False)
new_friend.address = new_address
new_friend.save()
return HttpResponseRedirect('/xcard/address_book')
else:
return render(request, 'xcard/add_address.html', {'state' : "Failed", 'friend_form':friend_form, 'address_form':address_form})
Templates:
address_book.html
{% include "xcard/header.html" %}
{% block main %}
<div class="container">
<h3 class="text-info"><u>Your Account</u></h3>
Add
Import
</div>
{% endblock %}
Templates:
login.html
{% extends "xcard/base.html" %}
{% block main %}
<div class="container">
<div class="row space">
<p class="text-center lead text-warning">
Login page</p>
<p class="text-center text-info">Trusted worldwide!</p>
</div>
<div class="row">
<div class="span offset4">
<form class="well" action="/xcard/login/" method="post">
{% csrf_token %}
<p class="lead">Sign In</p>
<fieldset class="login_page">
<p class="text-error"><strong>{{ state }}</strong></p>
<label class="control-label" for ="inputIcon">Email</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="span3" id="ernainputIcon" required name="username" placeholder="Username...."/><br/><br/>
</div>
</div>
<label>Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" class="span3" id="inputIcon" required name="password" placeholder="Password...."/><br/><br/><br />
</div>
</div>
<button class="btn btn-primary">Sign In</button>
Not a user?
Sign up
</fieldset>
</form>
</div>
</div>
</div>
{% endblock %}
I just found this in my urls.py
url(r'^add_address/$', login_required(AddAddressView.as_view(), login_url='/xcard/login/')),
Maybe this is causing the problem? But why doesn't it register that I'm already logged in?
first do the correction in AddAddressView function. update line
return render(request, 'xcard/add_address.html', {'friend_form':friend_form, 'address_form':address_form})
it will work
This was my solution - logout before you try to authenticate.
This issue happened to me when users were logging in and logging back in with a different username.
import django.contrib.auth as djangoAuth
djangoAuth.logout(request) # logout
user = djangoAuth.authenticate(username=username, password=password) # login