How to autofill form based on the selected 'id' in django - python

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

Related

Making with a POST request with checkboxes

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.

How to fix "Forbidden (403) CSRF verification failed. Request aborted." error in django

I'm getting this common error as in the title. I'm doing a project in Django in a virtual environment folder.
setting.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
index.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Instapic</title>
<link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
</head>
<body>
<div class="login-clean">
<form method="post">
{% csrf_token %}
<h2 class="sr-only">Login Form</h2>
<div class="illustration">
<div style="display: none" id="errors" class="well form-error-message"></div>
<img src="{% static 'assets/img/logo.jpg' %}">
</div>
<div class="form-group">
<input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">
</div>
<div class="form-group">
<input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">
</div>
<div class="form-group">
<input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>
</div>Already got an account? Login here ...</form>
</div>
<script src="{% static 'assets/js/jquery.min.js' %}"></script>
<script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
<script src={% static "assets/js/django-ajax.js" %}></script>
<script type="text/javascript">
$(document).ready(function() {
$('#go').click(function() {
$.post("ajax-sign-up",
{
username: $("#username").val(),
email: $("#email").val(),
password: $("#password").val()
},
function(data, status){
if (JSON.parse(data).Status == 'Success') {
window.location = '/';
} else {
$('#errors').html("<span>" + JSON.parse(data).Message + "</span>")
$('#errors').css('display', 'block')
}
});
return false;
})
})
</script>
</body>
</html>
I added {% csrf_token %} in my html file trying fix this - didn't work. I've found online this tag example:
<input type="hidden" id="csrf_token" value='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>.
Unfortunately I don't know how to use it in order to fix my error.
Thanks for help
I guess, instead of post a form you are posting values.
You need to add csrfmiddlewaretoken key while execute $.post() statement.
This is not Tested but it may be fix your problem
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value
or
csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
add this line in HTML file by updating
$.post("ajax-sign-up",
{
username: $("#username").val(),
email: $("#email").val(),
password: $("#password"),
csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
},
updated code is :
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Instapic</title>
<link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
</head>
<body>
<div class="login-clean">
<form method="post">
{% csrf_token %}
<h2 class="sr-only">Login Form</h2>
<div class="illustration">
<div style="display: none" id="errors" class="well form-error-message"></div>
<img src="{% static 'assets/img/logo.jpg' %}">
</div>
<div class="form-group">
<input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">
</div>
<div class="form-group">
<input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">
</div>
<div class="form-group">
<input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>
</div>Already got an account? Login here ...</form>
</div>
<script src="{% static 'assets/js/jquery.min.js' %}"></script>
<script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script>
<script src={% static "assets/js/django-ajax.js" %}></script>
<script type="text/javascript">
$(document).ready(function() {
$('#go').click(function() {
$.post("ajax-sign-up",
{
username: $("#username").val(),
email: $("#email").val(),
password: $("#password").val(),
csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val()
},
function(data, status){
if (JSON.parse(data).Status == 'Success') {
window.location = '/';
} else {
$('#errors').html("<span>" + JSON.parse(data).Message + "</span>")
$('#errors').css('display', 'block')
}
});
return false;
})
})
</script>
</body>
</html>
If you're just posting the contents of a HTML form with id signup-form (add that to the <form>), and your form has the {% csrf_token %}, then you can do that in ajax using:
$.post("ajax-sign-up", $("#signup-form").serialize(), function(data, status){...})

How can I connect the Submit button to my .py file?

The goal of my program is to place the first and last name into my database upon it being entered and Submit button clicked by the user so that when I manually check in Terminal what’s in my database, I can see what the user has entered and submitted. I need to some how connect my Submit button to my views.py file so that it can go through , sort like an onClick() but this time, to go a .py file. (correct me if I’m wrong with this train of thought).
How would I go about making this happen?
Here's my views.py file:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Person
def index(request):
if request.method == 'POST':
first_name = request.POST.get('firstName')
last_name = request.POST.get('lastName')
if first_name and last_name:
user = Person.objects.create(firstName=first_name, lastName=last_name)
user.save()
return render(request, 'music/index.html')
def detail(request, user_id): # Testing out page 2
return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>")
Here's my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="email" class="form-control" id="firstName" placeholder="Enter first name" name="firstName">
</div>
<div class="form-group">
<label for="">Last Name:</label>
<input type="email" class="form-control" id="lastName" placeholder="Enter last name" name="lastName">
</div>
</form>
<div class="checkbox">
<label><input type="checkbox" name="remember">Remember me</label></div></br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</body>
</html>
your form should be declared as:
<form method="POST">
and your <button type="submit"> should be inside the <form></form>.
As the same view deals with the GET and POST methods, you should remove the action="#" attribute, that way action will point to the same view.

Why won't my index.html file be found in directory?

I'm 100% sure my path is correct in my code, why is it giving me TemplateDoesNotExist error? I can't see how this is possible.
I tried:
settings.py > TEMPLATES > Dirs: [/template/music]
and a laundry list of other things on SO but it doesn't rectify my problem.
Here's my views.py file:
from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('music/index.html')
return HttpResponse(template.render())
def detail(request, user_id): # Testing out page 2
return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>")
Here's my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="email" class="form-control" id="firstName" placeholder="Enter first name" name="firstName">
</div>
<div class="form-group">
<label for="">Last Name:</label>
<input type="email" class="form-control" id="lastName" placeholder="Enter last name" name="lastName">
</div>
</form>
<div class="checkbox">
<label><input type="checkbox" name="remember">Remember me</label></div></br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</body>
</html>
Your templates directory is inside migrations. Move it out of there.

Save markdown content in simplemde

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)

Categories

Resources