My codes are running and insert the user information in the database(MySQL) but the login cannot work. These codes are bellow.
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<link href="https://fonts.googleapis.com/css2?family=Jost:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<div class="main">
<input type="checkbox" id="chk" aria-hidden="true">
<div class="signup">
<form method="post">
<label for="chk" aria-hidden="false">Sign up</label>
<input type="text" name="txt" placeholder="User name" required="">
<input type="text" name="email" placeholder="Email" required="">
<input type="password" name="pswd" placeholder="Password" required="">
<button id="button-1" onclikc="main_page()" href="/ ">Sign up</button>
</form>
</div>
<div class="login">
<form method="get">
<label for="chk" aria-hidden="true">Login</label>
<input type="email" name="email_1" placeholder="Email" required="">
<input type="password" name="pswd_1" placeholder="Password" required="">
<button id="button-2" onclick="login()">Login</button>
</form>
</div>
</div>
</body>
</html>
MYSQL CODES
CREATE TABLE user_table (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(55) NOT NULL,
email VARCHAR(55) NOT NULL,
userpass VARCHAR(122) NOT NULL);
from flask
import Flask, render_template, request, redirect, session, flash, url_for, escape
from functools
import wraps
from flask_mysqldb
import MySQL
import MySQLdb.cursors
from sympy
import re
app = Flask(__name__, template_folder = "template")
app.config['MYSQL_HOST'] = ''
app.config['MYSQL_USER'] = 'user'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'db'
mysql = MySQL(app)
def register():
if request.method == "POST":
details = request.form
username = details['txt']
password = details['pswd']
email = details['email']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO user_info(username, email, userpass) VALUES (%s, %s, %s)", (username, email, password))
mysql.connection.commit()
cur.close()
return render_template("index.html")
#app.route('/', methods = ["GET", "POST"])
def mainpage():
return register()
#app.route("/", methods = ["POST"])
#app.route("/home", methods = ["GET"])
def login():
if request.method == "POST":
email = request.form["email_1"]
pwd = request.form["pswd_1"]
cur = mysql.connection.cursor()
cur.execute("select * from user_info where email=%s and userpass=%s", (email, pwd))
data = cur.fetchone()
if data:
session['logged_in'] = True
session['username'] = data["username"]
else :
msg = "invalid login"
flash("yanlış bilgi!!", "error_message")
return render_template('home.html', status = True)
def is_logged_in(f):
#wraps(f)
def wrap( * argws, ** kwargs):
if 'logged_in' in session:
return f( * argws, ** kwargs)
else :
return redirect(url_for('login'))
#app.route("/logout")
def logout():
session.clear()
flash('You are now logged out', 'success')
return redirect(url_for('login'))
if __name__ == '__main__':
app.secret_key = "secret_key"
app.run(debug = True)
Can you help me to find the error or How can i connect the another screen in after clicking to the login button. Additionally I cant fix the problems about that data duplication and any message that visualization on the html screen.
Thank you :)
Related
In the inbox.js file I am trying to listen for a click event for each email single_email_div and send it to the email view in views.py
inbox.js
function load_mailbox(mailbox) {
// Show the mailbox and hide other views
document.querySelector("#emails-view").style.display = "block";
document.querySelector("#compose-view").style.display = "none";
// Show the mailbox name
document.querySelector("#emails-view").innerHTML = `<h3>${
mailbox.charAt(0).toUpperCase() + mailbox.slice(1)
}</h3>`;
// Show the emails of that particular mailbox
fetch(`/emails/${mailbox}`)
.then(response => response.json())
.then(emails => {
// Print emails
console.log(emails);
// ... do something else with emails ...
emails.forEach(email => {
const single_email_div = document.createElement('div');
single_email_div.innerHTML = `<a href="{%url 'email' email.id %}">
<br> ${email.id} <br>
From: ${email.sender} <br>
Subject: ${email.subject} <br>
TimeStamp: ${email.timestamp} <br>
Read: ${email.read} <br><br>
</a>`
if(`${email.read}` === false)
{single_email_div.style.backgroundColor = "white";}
else
{single_email_div.style.backgroundColor = "grey";}
const emails_div = document.querySelector('#emails-view');
emails_div.append(single_email_div);
// When a user clicks on an email, the user should be taken to a view where they see the content of that email
document.querySelector("single_email_div").addEventListener('click', () => {
fetch(`/emails/${id}`)
.then(response => response.json())
.then(email => {
// show email and hide other views
document.querySelector("#emails-view").style.display = "none";
document.querySelector("#compose-view").style.display = "none";
document.querySelector("#email-view").style.display = "block";
// display email
const view = document.querySelector("#email-view");
view.innerHTML =
`<ul>
<li> From: ${email.sender} </li>
<li> To: ${email.recipients} </li>
<li> Subject: ${email.subject} </li>
<li> TimeStamp: ${email.timestamp} </li>
<li> Body: ${email.body} <br><br>
</ul>`
});
})
});
})
return false;
}
inbox.html
{% block body %}
<h2>{{ request.user.email }}</h2>
<button class="btn btn-sm btn-outline-primary" id="inbox">Inbox</button>
<button class="btn btn-sm btn-outline-primary" id="compose">Compose</button>
<button class="btn btn-sm btn-outline-primary" id="sent">Sent</button>
<button class="btn btn-sm btn-outline-primary" id="archived">Archived</button>
<a class="btn btn-sm btn-outline-primary" href="{% url 'logout' %}">Log Out</a>
<hr>
<div id="emails-view"> </div>
<div id="email-view"> </div>
<div id="compose-view">
<h3>New Email</h3>
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" class="btn btn-primary"/>
</form>
</div>
{% endblock %}
{% block script %}
<script src="{% static 'mail/inbox.js' %}"></script>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
# API Routes
path("emails", views.compose, name="compose"),
path("emails/<int:email_id>", views.email, name="email"),
path("emails/<str:mailbox>", views.mailbox, name="mailbox"),
]
views.py
#login_required
def mailbox(request, mailbox):
# Filter emails returned based on mailbox
if mailbox == "inbox":
emails = Email.objects.filter(
user=request.user, recipients=request.user, archived=False
)
elif mailbox == "sent":
emails = Email.objects.filter(
user=request.user, sender=request.user
)
elif mailbox == "archive":
emails = Email.objects.filter(
user=request.user, recipients=request.user, archived=True
)
else:
return JsonResponse({"error": "Invalid mailbox."}, status=400)
# Return emails in reverse chronologial order
emails = emails.order_by("-timestamp").all()
return JsonResponse([email.serialize() for email in emails], safe=False)
#csrf_exempt
#login_required
def email(request, email_id):
# Query for requested email
try:
email = Email.objects.get(user=request.user, pk=email_id)
except Email.DoesNotExist:
return JsonResponse({"error": "Email not found."}, status=404)
# Return email contents
if request.method == "GET":
return JsonResponse(email.serialize())
# Update whether email is read or should be archived
elif request.method == "PUT":
data = json.loads(request.body)
if data.get("read") is not None:
email.read = data["read"]
if data.get("archived") is not None:
email.archived = data["archived"]
email.save()
return HttpResponse(status=204)
# Email must be via GET or PUT
else:
return JsonResponse({
"error": "GET or PUT request required."
}, status=400)
Below is the error that I keep getting:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/%7B%25url%20'email'%20email.id%20%25%7D
Using the URLconf defined in project3.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
login [name='login']
logout [name='logout']
register [name='register']
emails [name='compose']
emails/<int:email_id> [name='email']
emails/<str:mailbox> [name='mailbox']
The current path, {%url 'email' email.id %}, didn’t match any of these.
you are can not use django template tags "{% %}" in .js:
single_email_div.innerHTML = `<a href="{%url 'email' email.id %}">
Here you already should have
single_email_div.innerHTML = `<a href="/emails/${email.id}/">
I would like to show a small text confirming successful registration next to the "submit" button of the registration form. However it returns my html text on another page. I would like it to be shown on the same page, inside the "form" next to the "button". How do I do that. I'm using python flask. Here goes my code:
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '104041122'
app.config['MYSQL_DB'] = 'PAGINA10'
mysql = MySQL(app)
#app.route('/', methods=['GET', 'POST'])
def form():
if request.method == 'POST':
digitado = request.form
nome = digitado['nome']
cpf = digitado['cpf']
email = digitado['email']
birth = digitado['birth']
cursor = mysql.connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS pagina10 (nome VARCHAR(50) NOT NULL, cpf VARCHAR(11) NOT NULL, email VARCHAR(20) NOT NULL, birth DATE NOT NULL)")
cursor.execute("INSERT INTO pagina10 (nome, cpf, email, birth) VALUES (%s, %s, %s, %s)", (nome, cpf, email, birth))
mysql.connection.commit()
cursor.close()
return '<h1> Dados cadastrados com sucesso </h1>'
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
And here is my html page:
<form method="POST" action="">
<div>
<i class="fa-solid fa-pen"></i>
<input type="text" required name="nome" autofocus placeholder="Nome" data-ls-module="charCounter" maxlength="50" minlength="3"/>
</div>
<div>
<i class="fa-solid fa-id-card"></i>
<input type="text" required name="cpf" autofocus placeholder="CPF" minlength="11" maxlength="11"/>
</div>
<div>
<i class="fa-solid fa-at"></i>
<input type="email" required name="email" autofocus placeholder="E-mail" data-ls-module="charCounter" minlength="5" pattern="[UTF-8]">
</div>
<div>
<i class="fa-solid fa-cake-candles"></i>
<input type="date" required name="birth" autofocus placeholder="Nascimento">
</div>
<button type="submit">Cadastrar</button>
</form>
You can use the package flash from flask to show such messages on your website.
Your python code might look something like:
from flask import flash
#app.route('/registrierung', methods=['GET', 'POST'])
#app.route('/Registrierung', methods=['GET', 'POST'])
def registration_page(): # put application's code here
registration_form = RegistrationForm()
# ---------------------------------------------------
if registration_form.validate_on_submit():
print(registration_form.is_submitted())
# ----------------- Database Stuff -------------
flash(f'Account was created!', 'success')
return redirect(url_for('login_page'))
return render_template("registrierung.html", img_var_path=get_background_img_path(), registration_form=registration_form)
And you have to use something like this in your html code:
<!-- flash messages here -->
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div class="alert" id="hideMe">
{% for category, message in messages %}
<div class=" alert_{{ category }}">
{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
{% endwith %}
Problem:
If user is loggedin, I want to show greet user else show the form
and when the valid data is submitted, log in the user and
show greet message.
I am trying to pass the data on submit and update the user status to login. I tried with and without ajax but with both ways I could not figure out solution. Could you please help me why its failing? And how I can solve this?
HTML Form:
{% if user.is_authenticated %}
<h5 class="title billing-title ls-10 pt-1 pb-3 mb-0">
Welcome {{ user.username }}!
</h5>
{% else%}
<div class="login-toggle">
Returning customer? <a href="#"
class="show-login font-weight-bold text-uppercase text-dark">Login</a>
</div>
<form class="login-content" name="ajaxLogin" method="POST" action="{% url 'ecommerce:ajaxlogin' %}">
{% csrf_token %}
<p>If you have shopped with us before, please enter your details below.
If you are a new customer, please proceed to the Billing section.</p>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label>Username or email *</label>
<input type="text" class="form-control form-control-md" name="username" id="id_email"
required>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label>Password *</label>
<input type="password" class="form-control form-control-md" name="password" id="id_password"
required>
</div>
</div>
</div>
<div class="form-group checkbox">
<input type="checkbox" class="custom-checkbox" id="remember" name="remember">
<label for="remember" class="mb-0 lh-2">Remember me</label>
Lost your password?
</div>
<button class="btn btn-rounded btn-login" type="submit" >Login</button>
</form>
{% endif%}
Views.py :
def ajaxlogin(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(user=username, password=password)
if User.is_active and not None :
login(request)
else:
pass
return render('./ecommerce/checkout.html')
AJAX:
$(document).ready(function(){
$('.login-content').on('submit', function(event){
event.preventDefault();
var action_url = $(this).attr('action')
$.ajax({
url: action_url,
type:"POST",
data: $('.login-content').serialize(),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (data) {
console.log("login Successful");
},
});
});
});
Django authenticate takes keyword arguments username and password for the default case with request as optional parameter.
In your views.py you pass user as parameter in authenticate change it to username.
The default authentication returns None if user is in-active so you don't have to check for is_active if you are using default authentication.
Change your views.py as
def ajaxlogin(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None :
login(request, user)
else:
pass
return render('./ecommerce/checkout.html')
Also set contentType as application/x-www-form-urlencoded or leave it at the default by omitting the contentType key.
I am new to django and would like to write a simple log in web page
frontend: html, css, javascript(using bootstrap and jquery)
After filling the username and password and clicking the sign in button, it is supposed to jump to the home page.
Here is my code:
html:
<form id="sign-form" role="form">
{% csrf_token %}
<div class="form-group">
<label for="name" class="sr-only"> username </label>
<input id="name" type="text" class="form-control" placeholder="Username...">
</div>
<div class="form-group">
<label for="password" class="sr-only"> password </label>
<input id="password" type="password" class="form-control" placeholder="Password...">
</div>
<div class="form-group">
<button class="btn btn-block" id="sign-in-button"> Sign in </button>
</div>
<div class="form-group">
<button class="btn btn-block" id="sign-up-button"> Sign up </button>
</div>
</form>
js:
$("#sign-in-button").click(function () {
var name=$("#name").val();
var word=$("#password").val();
$.post("/login/",
{
'username': name,
'password': word
},
function (result) {
alert(result);
}
);
});
urls:
urlpatterns = [
path('admin/', admin.site.urls),
path(r'landing/', views.landing_page),
path(r'login/', views.login),
path(r'homepage/', views.home_page),
]
views:
def landing_page(request):
return render(request, "landingPage.html")
def login(request):
print("here log in")
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
print(username+" out")
if user is not None:
auth.login(request, user)
print(username)
return render(request, "homePage.html", {'username': username})
return render(request, "homePage.html")
return render(request, "homePage.html")
But I encountered this problem(please have a look at the pictures):
The remote host forced the closure of an existing connection
The remote host forced the closure of an existing connection
The remote host forced the closure of an existing connection
Can anybody help me ??
I want to find a way to submit a form without refreshing the current page at all using Python and jQuery. In the same page I have two forms.I created a forms using WTForms. The question is how can I save data on the first form without refreshing the page, that means that the fields should not become empty. I tried using the code below, but it save data from the first form, but it returns empty fields.
$('#target').click(function() {
$('#return').html("Patient is registered")
});
$('#target').click(function(){
$('#forma_patient').submit();
});
The first form is like this:
<form action=" {{ url_for('malingnant_disease.save_patient') }}" method="post" id="patient_form" class="form-horizontal patient">
<div>
<div>
<div class="form-group">
{{ form.name.label(class_="control-label col-xs-4") }}
<div class="col-xs-4">
{{ form.name(class_="form-control") }}
</div>
</div>
<div class="form-group">
{{form.surname.label(class_="control-label col-xs-4") }}
<div class="col-xs-4">
{{ form.surname(class_="form-control") }}
</div>
</div>
<div class="form-group">
{{ form.id.label(class_="control-label col-xs-4") }}
<div class="col-xs-4">
{{ form.id(class_="form-control") }}
</div>
</div>
</div>
<br />
<div id="return_answer" \>
<br/>
<div align="center">
<button type="submit" id="target" class="btn btn-primary">Save Patient</button>
The second one is defined with some fields...
<form action=" {{ url_for('malingnant_disease.save_diagnosis') }}" method="post" id="diagnosis_form" class="form-horizontal diagnosis">
<div>
<div>
<!-- some fields ....-->
</div>
<div align="center">
<button type="submit" class="btn btn-primary">Save diagnosis</button>
On the view page i have the route that define saving those data :
#mod_malignant_disease.route('/save', methods=['POST','GET'])
def save_patient():
malignant_disease = MalignantDiseaseForm(request.form)
malingnant_disease_data = malignant_disease.data
doc_id = utils.get_doc_id()
json_obj = {}
json_obj = {
'patient': {
'name': malingnant_disease_data['name'],
'surname': malingnant_disease_data['surname'],
'id': malingnant_disease_data['id']
}
};
mongo.db.malignantdisease.update(
{'_id': doc_id},
{'$set': json_obj},
True
)
return redirect(url_for('malingnant_disease.malingnant_disease_page'))
You'll need to use ajax to send a post without reloading the page. You can use jquery's post and serialize helpers for that. Instead of $('#forma_patient').submit(); use something like:
$.post( "/save", $('#patient_form').serialize(), function() {
alert( "success" );
});
U need use Ajax. Simple code for example. Check username and password not refresh page and get backbone result and view current page.
javascriptt
var EXAMPLES = {};
EXAMPLES.checkUsernamePasswordAjax = function (usernameid, passwordid, idresultlabel) {
var xhr = new XMLHttpRequest();
var username = document.getElementById(usernameid);
var password = document.getElementById(passwordid);
var result_label = document.getElementById(idresultlabel);
if (username && password) {
xhr.open('get', '/checker?username=' + username.value + "&password=" + password.value, true);
xhr.send(null);
xhr.onreadystatechange = function () {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
var result = JSON.parse(xhr.responseText);
result_label.innerHTML = result.answer;
}
};
}
};
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="{{ url_for('static', filename="js/exampleJS.js") }}" type="text/javascript"></script>
</head>
<body>
<form method="post" action="#" onchange="EXAMPLES.checkUsernamePasswordAjax('iduser', 'idpass');">
Username: {{ form.username(id="iduser") }} <br/>
Password: {{ form.password(id="idpass") }}
<hr/>
<strong>Result validation: </strong> <label id="idresult"></label>
{# <input type="submit" value="Check"/>#}
</form>
python/flask
#app.route('/checker/', methods=['get'])
#app.route('/checker/<username>', methods=['get'])
def login(username=None):
username, password = request.args['username'], request.args['password']
if username == "hacker" and password == "hacked":
return redirect(url_for('.hacker_page'))
return jsonify({'answer': 'False'})
#app.route('/hacked')
def hacker_page():
return jsonify({"answer": "<strong> <h2> hacked page </h2> </strong>"})
#app.route('/')
def root(api=None):
form = SimpleForm(request.form)
return render_template('index.html', form=form)
Enjoy, Dude :)