Data is not being sent from front end to back end and im using Html and ajax for the front end and linking up part
//signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src= "../static/jquery-3.3.1.min.js"></script>
<script src= "../static/sha1.min.js"></script>
<script src = "../static/sha1.js"></script>
<script>
$(function(){
$('.btnblock').click(function(){
var user = $('#inputUsername').val();
var pass = sha1($('#inputPassword').val());
//alert(pass);
//alert(JSON.stringify({username : user, password : pass}))
$.ajax({
url : 'http://localhost:5000/api/v1/users',
data : JSON.stringify({username : user, password : pass}),
type : 'POST',
method : 'post',
ContentType : 'text/plain',
dataType: 'json',
success: function(response){
alert(response);
},
error: function(error){
alert(error);
}
});
});
});
</script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<center>
<h1> Add user. </h1>
</center>
</head>
<body background="{{ url_for('static', filename='home/background.jpeg')}}">
<div class="container">
<form class="form-signin" enctype="multipart/form-data" role="form">
<input type="text" id="inputUsername" name="username" class="form-control" placeholder="Username" required autofocus>
<br>
<br>
<input type="password" id="inputPassword" name="password" class="form-control" placeholder="Password" required>
<br>
<br>
<button class="btnblock" type="submit">Register</button>
</form>
</div>
</body>
</html>
and the code which process these requests from the frontend is:
def addUser():
if(request.method == 'POST'):
##print(request._dict_)
print("Receiving data....")
data = request.data.decode()
print(data)
the problem here is what ever credentials and data added in the front-end isn't getting processed in the back-end, print(request.data) returns empty and does not return the added data each time and i did try debugging it a few times and googling what would the mistake be but still got no progress , Thank you for the assistance
Related
I am trying to pass in a list of classes into a checkbox (this works), and when the Submit button is clicked, I want to make a Post Request to send all the selected boxes to the backend and then also go to the next page (Does not work).
Here is my HTML page right:
<!doctype html>
<html lang="en">
<head>
<style>
h1 {color: rgb(240, 112, 38);}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
function myFunction() {
window.location.href="./classinfo";
}
function sendPOST() {
let formData = { user_classes: $("#user_classes").val() };
$.post("/class", formData)
};
</script>
</head>
<body style="background-color:powderblue;">
<div class="container">
<br>
<h1>What Classes Have You Taken</h1>
<div class="form-group row">
<label class="col-lg-12">
<form method="POST" action='/class'>
<label class="col-xs-6" style="font-family:verdana;">
{% for c in cs_req %}
<input type="checkbox" style="text-align:left;" name = 'user_classes' option value = "{{c}}" SELECTED> {{c}}<br></option>
{% endfor %}
</label>
<br>
<input class="btn btn-secondary" style="font-family:verdana;" type="Submit" onclick="sendPOST();MyFunction()">
</form>
</label>
</div>
<div id="content">
</div>
</div>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
})
</script>
</body>
</html>
and my backend function is this:
#app.route('/class', methods=["POST"])
def store_classes():
"'Based on checkboxes selected from checkboxes(), store the classes in txt'"
user_classes = request.form.getlist('class') #--> returns nothing
return render_template("class.html")
My onclick is not sending the post request or going to the next page. I'm not sure how to solve this so any advice is appreciated.
I have a form like this:
how to fill the disabled form field based on the selected 'No. Pelayanan'. This 'No.Pelayanan' is a select field, so when i choose (fill the field) it's autofill the form. i'm looking for any reference to how to do this. thank you!
This can be done via plain javascript or a little more conveniently using jquery. I will proceed with plain javascript.
you can store the corresponding data for your fields in a js variable or call an api based on your requirement and updated fields from there on changing the select field value.
You can use javascripts inputObject.value to set value of an input field as explained here
Here is a working example just for your reference on how this can be done
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css"
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<label for="emailfield">Email</label>
<input
type="email"
class="form-control"
id="emailfield"
placeholder="name#example.com"
disabled
/>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1"
>Example select</label
>
<select class="form-control" id="userselect">
<option value="1">user 1</option>
<option value="2">user 2</option>
<option value="3">user 3</option>
<option value="4">user 4</option>
<option value="5">user 5</option>
</select>
</div>
<div class="form-group">
<label for="fn">First Name</label>
<input
type="text"
class="form-control"
id="fn"
placeholder="firstname"
disabled
/>
</div>
<div class="form-group">
<label for="ln">Last Name</label>
<input
type="text"
class="form-control"
id="ln"
placeholder="lastname"
disabled
/>
</div>
</form>
</div>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
crossorigin="anonymous"
></script>
<script>
let usersData = [
{
id: 1,
email: "u1#gmail.com",
fname: "fname-1",
lname: "lname-1",
},
{
id: 2,
email: "u2#gmail.com",
fname: "fname-2",
lname: "lname-2",
},
{
id: 3,
email: "u3#gmail.com",
fname: "fname-3",
lname: "lname-3",
},
{
id: 4,
email: "u4#gmail.com",
fname: "fname-4",
lname: "lname-4",
},
{
id: 5,
email: "u5#gmail.com",
fname: "fname-5",
lname: "lname-5",
},
];
document.getElementById('userselect').onchange = (e) => {
let selectedUser = usersData.find(userdata => userdata.id == e.target.value);
console.log(selectedUser);
document.getElementById('emailfield').value = selectedUser.email;
document.getElementById('fn').value = selectedUser.fname;
document.getElementById('ln').value = selectedUser.lname;
};
</script>
</body>
</html>
Please ignore css classes used by me if you don't know about bootstrap as they are just for presentation. The other input fields such as dropdowns, textfields, checkboxes can be filled using js in the similary way.
For more example you can refer this
To know how this can done using jquery you can check this out
i am new to django/python
i am trying to change user password but i am getting error
Method Not Allowed (POST): /password_change_done
Method Not Allowed: /password_change_done
[23/Jul/2020 19:11:05] "POST /password_change_done HTTP/1.1" 405 0
this is my url patterns just for password changes :
path('password_change',
auth_views.PasswordChangeView.as_view(template_name='password_change.html'),
name='password_change'),
path('password_change_done',
auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html'),
name='password_change_done'),
both my html pages for this operation
my html code: password_change
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h3> Change Password</h3>
<form action="{% url 'password_change_done' %}" method="POST" class="form-signin">{% csrf_token %}
<input name="Old password" class="form_control" placeholder="Old password"
type="password" id=old_password required="true">
<input name="new password" class="form_control" placeholder="new password"
type="password" id=new_password required="true">
<input name="confirm password" class="form_control" placeholder="confirm password"
type="password" id=confirm_password required="true">
<button type="submit">Update</button>
</form>
</body>
</html>
my html code for password_chang_done:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
<h2> <img src="{% static 'images/welcome.jpg' %}"> </h2>
<h5>hello,{{request.user.username}}</h5>
<script>
window.alert("password sucessfully changed")
</script>
</body>
</html>
You should make the POST request to the password_change endpoint, not the password_change_done` endpoint, so:
<form action="{% url 'password_change' %}" method="POST" class="form-signin">
…
</form>
In is quite common in Django web development, and in web development in general to make a POST to the same view that first generated the page with a GET request.
Furthermore the PasswordChangeView view uses the PasswordChangeForm [GitHub]:
class PasswordChangeForm(SetPasswordForm):
# …
field_order = ['old_password', 'new_password1', 'new_password2']
The name of the <input> elements thus should be old_password, new_password1, and new_password2:
<input name="old_password" class="form_control" placeholder="Old password" type="password" id=old_password required="true">
<input name="new_password1" class="form_control" placeholder="new password" type="password" id="new_password" required="true">
<input name="new_password2" class="form_control" placeholder="confirm password" type="password" id=confirm_password required="true">
Everytime i get the stu_name variable value from form without using is_valid() function then stu_name is always return value enter by user but with is_valid() stu_name is always None.I do some experiments and i found that is_valid() is always return false but why?
This is views.py file code.
from django.shortcuts import render
from django.http import HttpResponse
from .models import student
from .forms import student_data
def my_data(request):
stu_name=None
myform=student_data(request.POST)
if (request.method=="POST" and myform.is_valid()):
stu_name=myform.cleaned_data['user']
else:
myform=student_data
return render(request,'show.html',{'student':stu_name})
This is my html file where the form code is written.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form action="/payment/show/" method="POST">
{% csrf_token %}
<label for="">Name</label>
<input type="text" name="user" required>
<label for="">ID</label>
<input type="number" required>
<label for="">Address</label>
<input type="text" required>
<button type="submit">Add Me</button>
</form>
</div>
</body>
</html>
forms.py file code.
from django import forms
class student_data(forms.Form):
name=forms.CharField(widget=forms.TextInput,max_length=20)
id=forms.IntegerField(widget=forms.NumberInput,max_value=6)
address=forms.CharField(widget=forms.TextInput,max_length=50)
Modify your view
def my_data(request):
stu_name=None
myform=student_data(request.POST)
if (request.method=="POST" and myform.is_valid()):
stu_name=myform.cleaned_data['user']
else:
myform=student_data
return render(request,'show.html',{'student':stu_name,'form':myform})
In your html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form action="/payment/show/" method="POST">
{% csrf_token %}
{{ form.as_p}}
<button type="submit">Add Me</button>
</form>
</div>
</body>
</html>
and in your forms.py
class student_data(forms.Form):
name=forms.CharField(widget=forms.TextInput,max_length=20, required=True)
id=forms.IntegerField(widget=forms.NumberInput,max_value=6, required=True)
address=forms.CharField(widget=forms.TextInput,max_length=50, required=True)
I am trying to build a blog using flask. SimpleMDE is used as post editor(html code below). I want to save the markdown content to local file and render by flask-misaka in jinja2.
In SimpleMDE, I can get raw markdown content by simplemde.value(). But when I pass simplemde.value() to var in javascript. "\n" is missing aftering passing. I think it may have some "magic" tools in javascript. The html code return 2 alert message, first message contains line feed, the second doesn't.
Could somebody give me some hits about this problems?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Editor</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel='stylesheet' href='.{{ url_for("static", filename="css/simplemde.min.css") }}'>
<script src='.{{ url_for("static", filename="js/simplemde.min.js") }}'></script>
</head>
<script type='text/javascript'>
function check() {
var raw = simplemde.value();
alert(raw);
document.testform.markdown_raw.value=raw;
alert(document.testform.markdown_raw.value);
}
</script>
<body>
<form method='post' class='form' role='form' name='testform'>
<div class="form-group " style="padding-top:10px">
<input class="form-control" id="post_title" name="post_title" type="text" value="Title?">
</div>
<div class="form-group">
<input class="form-control" id="markdown" name="post_content" type="textarea" value="">
</div>
<div class="form-group" style='display:none'>
<input class="form-control" id="markdown_raw" name="markdown_raw" type="textarea" value="Origin">
</div>
<div>
<input class='btn btn-default' onclick="check();" id='submit' name='submit' type='submit' value='Save'>
<input class='btn btn-default' id='publish' name='publish' type='submit' value='Publish'>
</div>
</form>
<script type='text/javascript'>
var simplemde = new SimpleMDE({ element: document.getElementById('markdown') });
</script>
</body>
</html>
If you want to get raw markdown, just use simplemde.value().
When you put raw markdown into normal textarea, it turns into pure text.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Editor</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
</head>
<body>
<form method='post' class='form' role='form' name='testform'>
<div class="form-group " style="padding-top:10px">
<input class="form-control" id="post_title" name="post_title" type="text" value="Title?">
</div>
<div class="form-group">
<textarea class="form-control" id="markdown" name="post_content"></textarea>
</div>
<div>
<input class='btn btn-default' onclick="" id='submit' name='submit' type='submit' value='Save'>
<input class='btn btn-default' id='publish' name='publish' type='submit' value='Publish'>
</div>
</form>
<script type='text/javascript'>
var simplemde = new SimpleMDE({ element: document.getElementById('markdown') });
</script>
</body>
</html>
Get the content:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def test():
if request.method == 'POST':
raw_md = request.form['post_content']
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)