Data not displaying from the flask sqlalchemy database - javascript

I want to display the data of a person that is inputted via a pop-up form. But for whatever reason, the data isn't showing up on the HTML page.
Here is the HTML code for the home page
{% block title %}Home{% endblock %}
{% block content %}
<!-- <script type="text/javascript" src="js/jquery.js"></script> -->
<!-- onclick="window.location.href='add-users'" -->
<head>
<link rel="stylesheet" href="{{ url_for('static',filename='add-users.css') }}" type="text/css"/>
<!-- <h4>Log out</h4> -->
<h1>
<div class="dropdown" style="position:absolute; top:80px; right:170px;">
<button class="btn btn-info dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ user.name }}
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu2">
<a style="text-decoration: none;"href="/logout"><button class="dropdown-item" type="button">Log Out</button></a>
<!-- <button class="dropdown-item" type="button">Switch Users</button>
<button class="dropdown-item" type="button">Something else here</button> -->
</div>
</div></h1>
<h1><button style="position:absolute; top:80px; right:100px; text-decoration: none"title="Add people" class="button" data-modal="modalOne"><span style="font-size:36px;">⊕</span></button></h1>
<div id="modalOne" class="modal">
<div class="modal-content">
<div class="contact-form">
<a class="close">⊗</a>
<form method="POST" action="/">
<h2>Add person</h2>
<br>
<!-- 2 column grid layout with text inputs for the first and last names -->
<div class="row mb-4">
<div class="col">
<div class="form-outline">
<input type="text" name="first_name" id="first_name" class="form-control" placeholder="First name"/>
</div>
</div>
<div class="col">
<div class="form-outline">
<input type="text" name="last_name" id="last_name" class="form-control" placeholder="Last name"/>
</div>
</div>
</div>
<!-- Email input -->
<div class="form-outline">
<input type="email" name="person_email" id="person_email" placeholder="Email" class="form-control" />
</div>
<!-- Address input -->
<div class="form-outline">
<input type="address" name="address" placeholder="Address" class="form-control" />
</div>
<div class="form-outline">
<input type="company" name="company" placeholder="Company" class="form-control" />
</div>
<div class="form-outline">
<input type="city" name="city" placeholder="City" class="form-control" />
</div>
<div class="form-outline">
<input type="county" name="county" placeholder="County" class="form-control" />
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</head>
<body>
<div id=container>
<ul class="list-group list-group-flush">
{% for item in user.person %}
{{ item.first_name }}
{% endfor %}
</ul>
</div>
</body>
<script type="text/javascript">
let modalBtns = [...document.querySelectorAll(".button")];
modalBtns.forEach(function (btn) {
btn.onclick = function () {
let modal = btn.getAttribute("data-modal");
document.getElementById(modal).style.display = "block";
};
});
let closeBtns = [...document.querySelectorAll(".close")];
closeBtns.forEach(function (btn) {
btn.onclick = function () {
let modal = btn.closest(".modal");
modal.style.display = "none";
};
});
window.onclick = function (event) {
if (event.target.className === "modal") {
event.target.style.display = "none";
}
};
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
{% endblock %}
Here is the code for models.py
from sqlalchemy import null
from . import __innit__ # importing from the package (website) the db
from flask_login import UserMixin
db = __innit__.db
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(20), unique=False, nullable=False)
last_name = db.Column(db.String(), unique=False, nullable=False)
# person_email = db.Column(db.String(), unique=False, nullable=False)
company = db.Column(db.String(), unique=False)
address = db.Column(db.String(), unique=False)
county = db.Column(db.String(), unique=False)
city = db.Column(db.String(), unique=False)
#image = db.Column(db.String(), unique=True, default="default.jpg")
user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
email = db.Column(db.String(), unique=True)
password = db.Column(db.String(150), nullable=False)
person = db.relationship("Person")
Here is the code for views.py
#views.route('/', methods=["GET", "POST"])
#login_required
def home(new_person):
if request.method == "POST":
first_name = request.form.get("first_name")
last_name = request.form.get("last_name")
person_email = request.form.get("person_email")
company = request.form.get("company")
address = request.form.get("address")
city = request.form.get("city")
county = request.form.get("county")
print(f"The first name is {first_name}")
if first_name == "":
flash("First name field empty", category="error")
elif last_name == "":
flash("Last name field empty", category="error")
elif person_email == "":
flash("Email field empty", category="error")
elif company == "":
flash("Company field empty", category="error")
elif address == "":
flash("Address field empty", category="error")
elif city == "":
flash("City field empty", category="error")
elif county == "":
flash("County field empty", category="error")
else:
new_person = Person(first_name=first_name, last_name=last_name, person_email=person_email, company=company, address=address, city=city, county=county, user_id=current_user.id)
db.session.add(new_person)
db.session.commit()
print("USER ADDED")
flash("New person added", category="success")
redirect(url_for("views.home"))
return render_template("second-home.html", user=current_user, new_person=new_person)
By the way the statement print(f"THe first name is {first_name}") isn't working, meaning the form isn't being accessed however when I hit the submit button, the terminal outputs a POST request
Here is the HTML page in which the data should be shown

It might be that you need to explicitly set the id value for each of the inputs in your modal. You have name specified, but I think id is a more stable option when collecting form data.
If you're running this locally in dev mode (via terminal/cmd line) I would absolutely suggest throwing a breakpoint() in before print(f"The first name is {first_name}") and look at what values request.form actually returns.

Related

Python Flask redirect after form is submited not working

I'm developing small Flask app that will take some data to form and after it is done will print it.
After form is submited it should redirect to different site (end point) but that is not happening.
I used return redirect(url_for('<name>')) and return render_template('<name>.html').
Inside form.html i use script to dynamically create new fileds if user needs it and submit actions is happening inside that script.
Code:
from flask import Flask, session, render_template, request, redirect, url_for
from os import urandom
app = Flask(__name__)
app.secret_key = urandom(24)
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return render_template('login.html')
#app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
#app.route('/')
def index():
login = False
if 'username' in session:
login = True
return render_template('login_home.html', login=login)
#app.route('/form')
def form():
if 'username' in session:
return render_template('form.html')
return redirect(url_for('index'))
#app.route("/getform", methods=["POST", "GET"])
def getform():
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
phone = request.form.get('phone')
address = request.form.get('address')
names = request.form.getlist('name[]')
emails = request.form.getlist('email[]')
print(name, email, phone, address, names, emails)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
and here is form.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Formular</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
var MaxInputs = 10; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div class="row"><p class="col-xs-6"><input type="text" placeholder="Unesite ime i prezime zaposlenika" class="form-control skill_list" name="name[]" id="field_'+ FieldCount +'"/><input type="email" placeholder="Unesite email zaposlenika" class="form-control skill_list" name="email[]" id="field_'+ FieldCount +'"/></p>×</div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
$('#submit').click(function(){
$.ajax({
url:"/getform",
method:"POST",
data:$('#add_skills').serialize()
});
});
});
</script>
<style>
.row {padding:10px;}
</style>
<div class="container"><br/> <br/>
<h2 align="center">Form</h2><div id="resultbox"></div>
<div class="form-group">
<form name="add_skills" id="add_skills">
<div class="form-group">
<input type="text" class="form-control" id="Name" aria-describedby="emailHelp"
placeholder="name" name="name" value="{{ name }}" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="address" aria-describedby="emailHelp"
placeholder="address" name="address" value="{{ address }}" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="phone" aria-describedby="emailHelp"
placeholder="phone" name="phone" value="{{ phone }}" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" aria-describedby="emailHelp"
placeholder="email" name="email" value="{{ email }}" required>
</div>
<label>Additional info:</label>
<div id="InputsWrapper">
<div class="row">
<div class="col-xs-6"><input type="text" name="name[]" placeholder="name" class="form-control name_list" />
<input type="email" name="email[]" placeholder="email" class="form-control name_list" /></div>
<div class="col-xs-6"><button type="button" name="add" id="AddMoreFileBox" class="btn btn-success">Add</button></div>
</div>
</div>
<br/>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
</div>
</div>
</body>
</html>
I will not post login.html and login_home.html because it is irelevant to this issue.
Problem is solved:
problem was in form.html:
I removed:
$('#submit').click(function(){
$.ajax({
url:"/getform",
method:"POST",
data:$('#add_skills').serialize()
});
});
added method="POST" and action="/form" to <form> tag:
<form name="add_skills" id="add_skills" action="/form" method="POST">
replaced:
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
with:
<button type="submit" class="btn btn-secondary">Submit</button>
in main.py added new endpoint with name form :
#app.route('/form', methods=["POST"])
def form():
name = request.form.get("name")
address = request.form.get("address")
telephone = request.form.get("phone")
email = request.form.get("email")
print(name, address, telephone, email)
return render_template("login_home.html")
So this solves my problem :)
I hope this will help someone with similar problem to mine.

JavaScript submit not working Django From

I have a simple form that uses JavaScript to validate and submit the form using POST to the database.
The script works for 2 forms but won't submit for other forms for some reason and I can't work out why. I've even copied the existing form and JS replaced it with new names and it still doesn't work and I cannot figure out why. I've tried to debug, but I'm getting http200 for every request so not throwing any errors that I can see.
Working version:
var investor_form = document.getElementById("add-investor");
investor_form.addEventListener("submit", function (e) {
e.preventDefault();
if (validated(this)) {
this.classList.add("was-validated");
var i_name = document.getElementById("investor-name").value;
var i_website = document.getElementById("investor-website").value;
var i_portfolio = document.getElementById("investor-portfolio").value;
var i_comment = document.getElementById("ckeditor-classic").value;
const csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
const formdata = new FormData();
formdata.append("investor_name", i_name);
formdata.append("investor_website", i_website);
formdata.append("investor_portfolio", i_portfolio);
formdata.append("investor_comment", i_comment);
const xhr = new XMLHttpRequest();
xhr.open("POST", "/apps/add_investor");
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send(formdata);
xhr.onload = () => {
window.location.reload();
};
}
})
// Form validation
function validated(form) {
console.log(form)
var i_name = document.getElementById("investor-name");
var i_website = document.getElementById("investor-website");
var i_portfolio = document.getElementById("investor-portfolio");
i_name_value = i_name.value.trim();
i_website_value = i_website.value.trim();
i_portfolio_value = i_portfolio.value.trim();
if (i_name_value === "") {
message = "Please fill investor name field"
setErrorFor(i_name, message);
} else {
setSuccessFor(i_name)
}
if (i_website_value === "") {
message = "Please fill investor website field"
setErrorFor(i_website, message);
} else if (!isUrl(i_website_value)) {
message = "Website is not valid"
setErrorFor(i_website, message);
} else {
setSuccessFor(i_website)
}
if (i_portfolio_value === "") {
message = "Please fill investor portfolio field"
setErrorFor(i_portfolio, message);
} else if (!isUrl(i_portfolio_value)) {
message = "Porfolio is not valid"
setErrorFor(i_portfolio, message);
} else {
setSuccessFor(i_portfolio)
return true;
}
}
// For Display Eroor
function setErrorFor(element, message) {
element.classList.remove('is-valid');
element.classList.add('is-invalid');
parent = element.parentNode;
for (var i = 0; i < parent.childNodes.length; i++) {
if (parent.childNodes[i].className == "invalid-feedback") {
notes = parent.childNodes[i];
notes.innerHTML = message;
break;
}
}
}
// For success Message
function setSuccessFor(element) {
element.classList.remove('is-invalid');
element.classList.add('is-valid');
}
// Check URL Pattern
function isUrl(url) {
var re = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
return re.test(url)
}
Non-working version with name changes
// Project Form submit
var project_form = document.getElementById("add-project");
project_form.addEventListener("submit", function (e) {
e.preventDefault();
if (validated(this)) {
this.classList.add("was-validated");
var i_name = document.getElementById("project-name").value;
var i_website = document.getElementById("project-website").value;
var i_comment = document.getElementById("ckeditor-classic").value;
const csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
const formdata = new FormData();
formdata.append("project_name", i_name);
formdata.append("project-website", i_website);
formdata.append("project_comment", i_comment);
const xhr = new XMLHttpRequest();
xhr.open("POST", "/apps/add_project");
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send(formdata);
xhr.onload = () => {
window.location.reload();
};
}
})
// Form validation
function validated(form) {
console.log(form)
var i_name = document.getElementById("project-name");
var i_website = document.getElementById("project-website");
i_name_value = i_name.value.trim();
i_website_value = i_website.value.trim();
if (i_name_value === "") {
message = "Please fill project name field"
setErrorFor(i_name, message);
} else {
setSuccessFor(i_name)
}
if (i_website_value === "") {
message = "Please fill project website field"
setErrorFor(i_website, message);
} else if (!isUrl(i_website_value)) {
message = "Website is not valid"
setErrorFor(i_website, message);
} else {
setSuccessFor(i_website)
return true;
}
}
// For Display Eroor
function setErrorFor(element, message) {
element.classList.remove('is-valid');
element.classList.add('is-invalid');
parent = element.parentNode;
for (var i = 0; i < parent.childNodes.length; i++) {
if (parent.childNodes[i].className == "invalid-feedback") {
notes = parent.childNodes[i];
notes.innerHTML = message;
break;
}
}
}
// For success Message
function setSuccessFor(element) {
element.classList.remove('is-invalid');
element.classList.add('is-valid');
}
// Check URL Pattern
function isUrl(url) {
var re = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
return re.test(url)
}
I've just done a find and replace for investor to project and then I have created copies of the forms/model/views/urls etc and updated to project
but it just won't update the database.
If I go into Django admin I can manually add the records, so I know the migration has worked.
response when clicking submit
[30/Oct/2021 20:10:36] "GET /apps/add_project HTTP/1.1" 200 32840
[30/Oct/2021 20:10:59] "POST /apps/add_project HTTP/1.1" 200 59
[30/Oct/2021 20:10:59] "GET /apps/add_project HTTP/1.1" 200 32840
views.py
class addProjectView(View):
template_name = 'pages/add_project.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
def post(self, request, *args, **kwargs):
form = addProjectForm(request.POST)
if form.is_valid():
form.save()
data = {"success": "successfully added"}
else:
data = {"error": form.errors}
return JsonResponse(data, safe=False)
add_project_view = addProjectView.as_view()
Models.py
class Project(models.Model):
project_name = models.CharField(max_length=255, blank=False)
project_website = models.URLField(max_length=255, blank=False)
project_comment = models.TextField()
def __str__(self):
return str(self.project_name)
Forms.py
class addProjectForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(addProjectForm, self).__init__(*args, **kwargs)
class Meta:
model = Project
fields = '__all__'
form html add_project.html
{% extends 'partials/base.html' %}
{% load static %}
{% block head_title%}
<title>Add Project | Dashboard</title>
{% endblock %}
{% block content %}
<div class="main-content">
<div class="page-content">
<div class="container-fluid">
<!-- start page title -->
<div class="row">
<div class="col-12">
<div class="page-title-box d-sm-flex align-items-center justify-content-between">
<h4 class="mb-sm-0 font-size-50">Add Project</h4>
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item">Pages</li>
<li class="breadcrumb-item active">Project</li>
</ol>
</div>
</div>
</div>
</div>
<!-- end page title -->
</div> <!-- container-fluid -->
</div>
<div class="card-body">
<form class="needs-validation" id="add-project" novalidate method="post" enctype="multipart/form-data" onsubmit="return false;">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="project-name-label">Project Name</label>
<input type="text" class="form-control" id="project-name" placeholder="Project Name">
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Please fill project name.
</div>
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="project-url-input" class="form-label">Project Website</label>
<input class="form-control" type="url" placeholder="https://example.com" id="project-website">
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Please provide a valid web address.
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Comments</h4>
<p class="card-title-desc">Please add any comments or notes</p>
</div>
<div class="card-body">
<textarea id="ckeditor-classic"></textarea><br>
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</div>
</form>
<!-- end col -->
</div>
<button type="button" class="btn btn-primary" id="toastMessage" hidden></button>
<div class="position-fixed top-0 end-0 p-3" style="z-index: 11">
<div class="toast align-items-right text-white bg-primary border-0" id="toast-message" role="alert"
aria-live="assertive" aria-atomic="true">
<div class="d-flex">
<div class="toast-body">
Successfully added Project!
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
aria-label="Close"></button>
</div>
</div>
</div>
<!-- End Page-content -->
{% endblock %}
{% block extra_js %}
<!-- ckeditor -->
<script src="{% static 'libs/#ckeditor/ckeditor5-build-classic/build/ckeditor.js' %}"></script>
<!-- init js -->
<script src="{% static 'js/pages/form-editor.init.js' %}"></script>
<!-- pristine js -->
<script src="{% static 'libs/pristinejs/dist/pristine.min.js' %}"></script>
<!-- form validation and XHR call -->
<script src="{% static 'js/pages/project.init.js' %}"></script>
{% endblock %}
Any ideas why its not working or how I can debug this?
Thanks

Dynamically save the Django form

I am trying not to use formset in my form. Instead of that, I'm trying to create the form dynamically and save all forms data in the DB.
I can create a dynamic form, but whenever I create multiple forms in "create order", it always saves the last forms data. For example, once I create 3 forms, and after saving the form, the table shows me only 3rd form data, which means it does not save all data together.
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
forms = OrderForm(request.POST)
if forms.is_valid():
po_id = forms.cleaned_data['po_id']
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
part = forms.cleaned_data['part']
order = Order.objects.create(
po_id=po_id,
supplier=supplier,
product=product,
part=part,
)
forms.save()
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
forms.py
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['supplier', 'product', 'part','po_id']
widgets = {
'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}),
'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}),
'part': forms.Select(attrs={'class': 'form-control', 'id': 'part'}),
}
HTML
<form action="#" method="post" id="form-container" novalidate="novalidate">
{% csrf_token %}
<div class="form">
<div class="form-group">
<label for="po_id" class="control-label mb-1">ID</label>
{{ form.po_id }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div class="form-group">
<label for="part" class="control-label mb-1">Part Name</label>
{{ form.part }}
</div>
</div>
<button id="add-form" type="button">Add Another Order</button>
<div>
<button id="payment-button" type="submit" class="btn btn-lg btn-success btn-block">
<span id="payment-button-amount">Save</span>
</button>
</div>
</form>
<script>
let poForm = document.querySelectorAll(".form")
let container = document.querySelector("#form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let formNum = poForm.length-1
addButton.addEventListener('click', addForm)
function addForm(e){
e.preventDefault()
let newForm = poForm[0].cloneNode(true)
let formRegex = RegExp(`form-(\\d){1}-`,'g')
formNum++
newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)
container.insertBefore(newForm, addButton)
totalForms.setAttribute('value', `${formNum+1}`)
}
</script>
What causes this problem? How can I fix it?

i try ajax partial refresh html,but it does't work

I'm trying to load the page locally with Ajax, but the following code doesn't work.
My idea is to pass the 'MSG' information of 'views' to Ajax and refresh the page locally without loading the entire page. If the input does not meet the requirements, the front end rejects the submission and gives a prompt message.
views.py
def login(request):
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
captcha = {'image_url': image_url, 'hashkey':hashkey}
if request.POST:
username = request.POST['username']
password = request.POST['password']
key = request.POST['hashkey']
capt = request.POST['captcha']
if username and password:
if captchautil.is_valid(capt, key):
user = auth.authenticate(username=username, password=password)
human = True
if user:
auth.login(request, user)
return redirect('/')
else:
msg = '用户名密码错误'
else:
msg = '请输入正确的验证码'
else:
msg = '请输入用户名与密码'
return render(request, 'login.html', locals())
return render(request, 'login.html', locals())
login.html
{% block content %}
<div id="login" class="login">
<form action="/login/" method="post" class="navbar-form">
{% csrf_token %}
<div id="input" class="form-group">
<input type="username" name="username" class="form-control" placeholder="请输入手机号或邮箱" id='user' title="请输入手机号或邮箱"><br><br>
<input type="password" name="password" class="form-control" placeholder="密码" id='pwd' title="请输入密码"><br><br>
<img src="{{image_url}}" alt='验证码' id='id_captcha'>
<span>看不清验证码?刷新</span>
<br>
<input id='captcha' placeholder="请输入验证码" name="captcha" class="form-control" type="text" data-toggle="tooltip" data-placement="bottom" title="请输入验证码">
<input value="{{hashkey}}" type="hidden" name="hashkey" id='hashkey'>
<br>
<button type="submit" class="btn btn-primary form-control" name="click" id='click'>登录</button>
</div>
<p style="margin-left: auto;" id="msg">{{ msg }}</p></div>
</form>
<div style="margin-left: 3%">
<span>
忘记密码了?
</span>
<span style="margin-left: 3%">免费注册</span>
</div>
</div>
{% endblock %}
{% block lastscript %}
<script type="text/javascript">
$(document).ready(function(){
//刷新验证码
$('#refresh_captcha').click(function(){
$.getJSON("/refresh_captcha/", function(result){
$('#id_captcha').attr('src', result['image_url']);
$('#hashkey').val(result['hashkey'])
});
});
});
$(function(){
$("#click").submit(function(){
var username = $("#user").val();
var password = $("#pwd").val();
var captcha = $("#captcha").val();
var key = $("#hashkey").val();
$(this).ajaxSubmit({
type:'post',
url: '/login/',
dataType: 'text',
data:{'username':username, "password":password, "capt":captcha, "key":key},
success:function(msg){
$("#msg").html(msg);
}
});
return false;
})
})
</script>
{% endblock %}
I didn't find out where the problem was. Please help me if you know
If you are fetching form dynamically and if you are trying to say like your javascript click functions are not working then you should try below.
$(document).on("click","#test-element",function() {
});
instead of normal click or submit an event
$("#click").submit(function(){ }); .
As per my knowledge if you are creating dynamic elements then the normal click event of jquery will not work. you need to write click event what added above.

Login Ajax form not working, redirecting to another page

I have created a Ajax form to handle the errors in my login form, but instead of showing errors in the form area, it directs me to another page with the json error response
<div class="container-fluid bg-primary" id="login">
<div class="row">
<div class="col-lg-3 text-center">
</div>
<div class="col-lg-6 text-center">
<h1> </h1><h3> </h3>
<h2 class="section-heading">Login to your profile</h2>
<hr>
</div>
<div class="col-lg-3 text-center">
</div>
<h2> </h2>
<h2> </h2>
<h2> </h2>
</div>
<div class="col-md-4 col-md-offset-4 ">
<form id='loginform' action='/users/login/' method='post' accept-charset='UTF-8'>
{% csrf_token %}
<fieldset >
<div class="form-group">
<input type="text" name="mobile_number" id="mobile_number" tabindex="1" class="form-control" placeholder="Mobile Number" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Enter Password">
</div>
</fieldset>
<button type="submit" class="btn btn-primary btn-xl btn-block">LOG IN</button><br><br>
<span class="login-error"></span>
<h1> </h1><h1> </h1>
</form>
</div>
My ajax code
$("#loginform").on('submit', function(event) {
event.preventDefault();
alert("Was preventDefault() called: " + event.isDefaultPrevented());
console.log("form submitted!");
var url = "/users/login-ajax/";
$.ajax({
type: "POST",
url:url,
data: $("#loginform").serialize(),
success: function(data)
{
console.log(data);
var result = JSON.stringify(data);
if(result.indexOf('errors')!=-1 ){
console.log(data);
if(data.errors[0] == "Mobile number and password don't match")
{
$('.login-error').text("Mobile number and password don't match");
}
else if(data.errors[0] == "Entered mobile number is not registered")
{
$('.login-error').text("Entered mobile number is not registered");
}
}
else
{
window.open("/users/profile/");
}
//var result = JSON.stringify(data);
// console.log(result);
}
})
});
My code for the action in views.py
def login(request):
if request.method == 'POST':
mobile_number = request.POST.get('mobile_number', '')
password = request.POST.get('password', '')
data = {}
user_queryset = User.objects.filter(mobile_number=mobile_number)
if len(user_queryset) == 0:
data['error'] = []
data['error'].append("Entered mobile number is not registered")
# return JsonResponse(data)
elif len(user_queryset) == 1:
email = user_queryset[0].email
user = auth.authenticate(email=email, password=password)
if user is not None:
auth.login(request, user)
else:
data['error'] = []
data['error'].append("Mobile number and password don't match")
return JsonResponse(data)

Categories