Django Form dropdown fill with values - javascript

I have a from with fields I created in Django models.py. One of the fields is:
res_person_1 = models.TextField(verbose_name="Odgovorna osoba 1")
HTML page is:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Prijavite nesukladnost</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Prijava</button>
</div>
</form>
</div>
When I inspect the HTML page, ID of object is 'id_res_person_1'. At the page load I run script to get from database all users, which should fill the 'res_person_1' field and that field should be dropdown.
Script is:
<script type="text/javascript">
var endpoint = '/call_jquery_korisnici/'
var korisnik_ime_prezime = []
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
korisnik_ime_prezime = data.korisnik_ime_prezime
console.log(korisnik_ime_prezime)
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
</script>
I don't know how to fill that field and how to make it dropdown. It doesn't work with:
$("#id_res_person_1").html(korisnik_ime_prezime);
document.getElementById('id_res_person_1').value = korisnik_ime_prezime;
If I console output var korisnik_ime_prezime: (2) ["TestName1 TestLastname1", "TestName2 TestLastname1"]

You can use replaceWith to replace your textarea with select-box then use each loop to iterate through your return response from server and then append option inside your select-box.
Demo code :
$(document).ready(function() {
var korisnik_ime_prezime = []
/*$.ajax({
method: "GET",
url: endpoint,
success: function(data) {*/
//just for demo
korisnik_ime_prezime = ["TestName1 TestLastname1", "TestName2 TestLastname1"] // data.korisnik_ime_prezime
//replcae textarea with slect
$("#id_res_person_1").replaceWith("<select name='id_res_person_1' id='id_res_person_1' class='form-control'></select>")
//loop
$(korisnik_ime_prezime).each(function(i) {
$("#id_res_person_1").append("<option>" + korisnik_ime_prezime[i] + "</option>") //append options
})
/*},
error: function(error_data) {
console.log("error")
console.log(error_data)
}
})*/
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form method="POST" enctype="multipart/form-data">
<textarea id="id_res_person_1"></textarea>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Prijava</button>
</div>
</form>

Related

Django/Js: how to post a form without reloading whole page

My application currently flows through 3 pages:
User selects question in index page
User submits answer in answer page
User is presented with result in results page.
I want to compress that down to a single page where the user submits an answer to the question and result is shown on the same page.
The following django-template code separates questions with Bootstrap accordion. How do I post the form without refreshing the whole page? I want to be able to display the result on the page, update CSS styling with Javascript etc.
<h2>{{ category.title }}</h2>
<div class="accordion" id="accordion{{category.title}}">
{% for challenge in category.challenge_set.all %}
<div class="card">
<div class="card-header" id="heading{{challenge.id}}">
<h2 class="mb-0">
<button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse{{challenge.id}}" aria-expanded="true" aria-controls="collapse{{challenge.id}}">
{{ challenge.question_text }} - {{ challenge.point_value }} points
</button>
</h2>
</div>
<div id="collapse{{challenge.id}}" class="collapse in" aria-labelledby="heading{{challenge.id}}" data-parent="#accordion{{category.title}}">
<div class="card-body">
<p>{{ challenge.description }}</p>
<form action="{% url 'challenges:answer' challenge.id %}" method="post">
{% if challenge|is_answered:request %}
<label for="answered">Answer</label>
<input type="text" name="answered" id="answered" value="{{ challenge.answer_text }}" readonly>
{% else %}
{% csrf_token %}
<label for="answer">Answer</label>
<input type="text" name="answer" id="answer">
<input type="submit" value="Submit">
{% endif %}
</form>
</div>
</div>
{% endfor %}
</div>
Here is the view:
def index(request):
context = {'challenges_by_category_list': Category.objects.all()}
return render(request, 'challenges/index.html', context)
def detail(request, challenge_id):
challenge = get_object_or_404(Challenge, pk=challenge_id)
return render(request, 'challenges/detail.html', {'challenge': challenge})
def results(request, challenge_id, result):
challenge = get_object_or_404(Challenge, pk=challenge_id)
return render(request, 'challenges/results.html', {'challenge':challenge, 'result':result})
def answer(request, challenge_id):
challenge = get_object_or_404(Challenge, pk=challenge_id)
result = "Incorrect, try again!"
if challenge.answer_text.lower() == request.POST['answer'].lower():
current_user = request.user
session = User_Challenge(user=current_user, challenge=challenge, answered=True)
session.save()
points = Profile(user=current_user, points=challenge.point_value)
points.save()
result = "Correct!"
return HttpResponseRedirect(reverse('challenges:results', args=(challenge.id, result)))
You can try this:
Add the below script in your template:
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
write a script and a function inside it to submit the form data.
<script type="text/javascript">
function submitData( challenge_id ){
// Get answer from the input element
var answer = document.getElementById("answer").value;
// add the url over here where you want to submit form & challenge_id is also taken as a parameter.
var url = "<your_url>";
$.ajax({
url: url,
data: {
'answer': answer,
},
dataType: 'JSON',
success: function(data){
// show an alert message when form is submitted and it gets a response from the view where result is provided and if url is provided then redirect the user to that url.
alert(data.result);
if (data.url){
window.open(data.url, '_self');
}
}
});
}
</script>
Change type of the submit button and add an onclick event to call the submitData() function and pass the challenge id to it. And remove the action attr from the form.
see below:
<form method="post">
{% csrf_token %}
{% if challenge|is_answered:request %}
<label for="answered">Answer</label>
<input type="text" name="answered" id="answered" value="{{ challenge.answer_text }}" readonly>
{% else %}
<label for="answer">Answer</label>
<input type="text" name="answer" id="answer">
// over here
<button type="button" onclick="submitData({{ challenge.id }})">
Submit
</button>
{% endif %}
</form>
Return a JsonReponse to the ajax call from the views.
views.py
def answer(request, challenge_id):
answer = request.GET.get('answer', False)
url = False
if challenge.objects.filter(id=challenge_id).exists() and answer:
challenge = Challenge.objects.get(id=challenge_id)
if challenge.answer_text.lower() == answer.lower():
current_user = request.user
session = User_Challenge(user=current_user, challenge=challenge, answered=True)
session.save()
points = Profile(user=current_user, points=challenge.point_value)
points.save()
result = "Correct!"
# specify the url where you want to redirect the user after correct answer
url = ""
else:
result = "Incorrect, try again!"
data = {
'result': result,
'url': url
}
return JsonResponse(data)

How to submit multiple forms in single submit

I have the following form created in my HTML, this will be submitted to "url 'submitrecord'". This will work fine for single entry per HTML. How can I add multiple entries of this type and submit at once.
Code:
<form method='POST' action="{% url 'submitrecord' %}">
<div class="row">
<div class = "col-md-1 form-group">
<input type="text" class="form-control" name="EntryNo" placeholder="EntryNo"/>
</div>
<div class = "col-md-2 form-group">
<input type="text" class="form-control" name="MedicineName" placeholder="MedicineName"/>
</div>
<button type="submit" class="btn btn-default">Done</button>
</div>
</form>
I found this answer but still it isnot sending the request to my URL.
<script>
$(document).ready(function(){
var called = 0;
ajax_recaller = function(forms){
$.ajax({
type: "POST",
data: forms[called].serialize(),
url: forms[called].attr('action'),
success: function(data) {
called++;
if(called < forms.length) {
ajax_recaller(forms);
} else {
called=0; // set called value to 0 again
alert('All forms has been submitted!');
}
}
});
}
$(document).on('click','.submitforms',function(){
var x=0;
$('.ajax_form').each(function(){
forms[x] = $(this);
x++;
});
ajax_recaller(forms);
});
});
</script>

Save data by submiting a form without refreshing/redirecting of the current page python

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 :)

Can't add comment with ajax

I'm trying to add comment using ajax.
Here is my ajax code:
$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = {{article.id}};
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "get",
success: function(result){
if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = "comment"><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
});
});
Here is my form of adding comment in django template:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>
Trying to debug, I noticed that it doesn't even step into ajax body. What am I doing wrong then?
I've done ajax query with counting likes and had success in that.
Try this
HTML
</div>
{% if username %}
<form action="#" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="text" name = "article" value="{{ article.id }}" id = "article_id">
<input type="text" name = "comment" value="comment goes here" id = "comment_text">
<input type="submit" class="button" value="???????? ???????????" id = "add_comment">
</form>
{% endif %}
</div>
jQuery
$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = $('#article_id').val();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "POST", /*i belive you are posting data to BE api*/
data:{'comment':"your comment goes here"}, /* use this get what given in input $("#comment_text").val()*/
success: function(result){
/*process data after success call*/
}
});
});
});
Change to the following:
JS Code:
$(document).ready(function(){
$("#comment_form").submit(function(event){
event.preventDefault();
var article_id = $(this).find('.article_id').value();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "post",
success: function(result){
if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = 'comment'><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
return false;
});
});
Django Template:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="hidden" class="article_id" value="{{ article.id }}" />
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>

Python/Django: Print message upon form submit

New to Django/Jquery:
Trying to print "Thanks for signing up!" after a form is submitted.
<script type="text/javascript">
$(function() {
$("input[data-submit-item]").live("click", function() {
var message = "Thanks for signing up!";
$.ajax({
type: "POST",
url: "/add",
data: {
"text": $("#item").val(),
"csrfmiddlewaretoken": $('input[name~="csrfmiddlewaretoken"]').val()
},
success: function(data) {
$("#item-list").append(data);
$("#confmessage").append(message);
$("#item").val("");
}
});
});
});
</script>
</head>
<body>
<div id = "main-container">
<h1>FooBar Baz</h1>
<div id = 'signup-form'>
<form>
<input type="text" id="item" placeholder="Enter your email ..." />
{% csrf_token %}
<div><input type="submit" value="Sign Up" data-submit-item="true" /></div>
</form>
</div>
<div id = "confmessage"></div>
<p><strong>front</strong></p>
<ul id="item-list">
{% for item in line %}
<li>{{ item.text }}</li>
{% endfor %}
</ul>
<p><strong>back</strong></p>
<p>remove</p>
</div>
</div>
</div>
</div>
</body>
</html>
This just prints out a list of all the entered emails but doesnt print the confirmation message. This is a modification of this example: https://github.com/memcachier/memcachier_line/blob/master/templates/index.html
You just need:
$("#confmessage").text(message);
instead of using append.

Categories

Resources