I am trying to learn using Jquery in django application.My code looks like this
views.py
from django.shortcuts import render
from django.http import HttpResponse
from airapp.models import Travel
def search_form(request):
return render(request, 'search_form.html')
def search(request):
if 'f' in request.GET and request.GET['f']:
q = request.GET['f']
books = Travel.objects.filter(froms__icontains=q)
return render(request, 'search_results.html',
{'books': books, 'query': q})
else:
return HttpResponse('Please submit a search term.')
urls.py
from django.conf.urls import patterns, include, url
from air import views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^search-form/$', views.search_form),
url(r'^search/$', views.search),
)
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
FROM<input type="text" name="f"><br>
TO<input type="text" name="t"><br>
CLASS<input type="text" name="c"><br>
<input type="submit" value="Search">
</form>
</body>
</html>
search_results.html
<p>You searched for: <strong>{{ query }}</strong></p>
{% if books %}
<p>Found {{ books|length }} book{{ books|pluralize }}.</p>
<ul>
{% for book in books %}
<li>{{ book.froms }}</li>
<li>{{ book.to}}</li>
<li>{{ book.classs }}</li>
<li>{{ book.details }}</li>
{% endfor %}
</ul>
{% else %}
<p>No books matched your search criteria.</p>
{% endif %}
When the search result displays it will be on a new html page(search_results.html).I want to display search results on the same html page where form is created(search_form.html) when I click search button.Can I display it using jquery? Can anybody help me write the code.
Also anybody suggest me good tutorial for learning ajax and jquery & how can I use it django
application development.
Here is an working sample. Just need to modify search_form.html:
<html>
<head>
<title>Search</title>
<script language="JavaScript" type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(function() {
$("#search-form").submit(function() {
var from = $("#search-form :input[name='f']").val();
$.get("/search/", { f : from })
.done(function(data) {
$("#search-result").html(data);
$("#search-result").show();
});
return false;
})});
</script>
</head>
<body>
<form id="search-form">
FROM<input type="text" name="f"><br>
TO<input type="text" name="t"><br>
CLASS<input type="text" name="c"><br>
<input type="submit" value="Search">
</form>
<div id="search-result" style="display:none">
</div>
</body>
</html>
Basically, what it does:
include jQuery in head
in the script, replace 'submit' behaviour of 'search-form': use $.get to send a GET request to server, and directly show response in 'search-result' div. (you may modify the codes to make it more robust)
in body, create a 'search-result' div for displaying response. Make it invisible by default (may do it in a CSS file)
For Ajax, you may refer to: http://api.jquery.com/jquery.ajax/. $.get is a shortcut based on $.ajax: http://api.jquery.com/jquery.get/
Related
I'm trying to make a stock finance like website where anyone can get fake money and buy stocks. So in the buy page, I am trying to implement a feature where as the user types the stock symbol and the number of shares, in real time, the pricing shows up in the h1 tags that have an id of "render". This can be achived if user input is sent to my app.py and after looking up the price using an api and some math, app.py send the price back to javascript to update the page.
I've been trying to use fetch() and AJAX but I don't understand any of the tutorials or stack overflow questions. Can someone give me a reliable solution and explain it to me?
HTML:
{% extends "layout.html" %}
{% block title %}Buy{% endblock %}
{% block main %}
<form action="/buy" method="post">
<div class="mb-3">
<input class="form-control mx-auto w-auto" autocomplete="off" name="symbol" placeholder="Symbol" value="{{ input_value }}" id="symbols">
</div>
<div class="mb-3">
<input class="form-control mx-auto w-auto" autocomplete="off" autofocus name="shares" placeholder="Shares" id="shares">
</div>
<div class="mb-3">
<button class="btn btn-primary" type="submit">Buy</button>
</div>
</form>
<h1 id="render">
</h1>
<script>
</script>
{% endblock %}
App.py:
#app.route("/buy", methods=["GET", "POST"])
#login_required
def buy():
"""Buy shares of stock"""
if request.method == "GET":
return render_template("buy.html", input_value = "")
else:
return render_template("buy.html", input_value = request.form.get("symbol"))
I'm trying to use the function above for rendering the template
Accepting response and sending back information:
#app.route("/show_price", methods=["GET", "POST"])
def show_price():
#logic stuff
return #price
TL;DR at bottom
I found a solution to the problem by using this as my app.py:
#app.route("/show_price", methods=["GET", "POST"])
#login_required
def show_price():
# https://www.makeuseof.com/tag/python-javascript-communicate-json/
data = request.get_json()
if data[1].isdigit() == True:
data = jsonify() # the data
return data
else:
return ""
and using fetch() in my javascript:
{% extends "layout.html" %}
{% block title %}Buy{% endblock %}
{% block main %}
<form action="/buy" method="post">
<div class="mb-3">
<input id="symbols">
</div>
<div class="mb-3">
<input id="shares">
</div>
<h2 id="render">
</h2>
<div class="mb-3">
<button class="btn btn-primary" type="submit">Buy</button>
</div>
</form>
<script>
let input1 = document.getElementById('symbols');
let input = document.getElementById('shares');
input.addEventListener('keyup', function(event) {
value = [
input1.value, input.value
]
fetch("http://127.0.0.1:5000/show_price",
{
method: 'POST',
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(value)}).then(res =>{
if(res.ok){
return res.json()
} else {
document.querySelector('h2').innerHTML = "Keep typing...";
}
}).then(jsonResponse=>{
word = "That would be " + jsonResponse
document.querySelector('h2').innerHTML = word;
})
.catch((err) => console.error(err));
});
</script>
{% endblock %}
so as the user is typing in the the shares field the event listener will get the symbols and shares fields, use fetch() to get the data over to def show_price() with a jsonified array of symbol and shares. If there is an error the div id="render" will display "Keep typing". After python gets the information it will look it up using a function, then it will return the price of the shares in json format. Then javascript will get the data and use some javascript to change the html.
TL;DR
Basically I used fetch() to get the data to python, did some algorithm stuff and python return it to javascript. https://www.makeuseof.com/tag/python-javascript-communicate-json/ is really useful in teaching you how to use fetch().
I'm trying to change the text inside an input field to username.
The id for the field is is_username.
And in my Javascript file I've tried
document.getElementById("id_username").innerHTML = "Username";
document.getElementById("id_username").value = "Username";
document.querySelector(".id_username").textContent = "Username";
None are working... This site runs on django.
I know with html you can use placeholder to achieve this but these fields are created using django tags.
Any ideas?
I did try using these methods on a normal html input field and also had no luck.
htmlpage:
{% extends 'display_words.html' %}
{% block content %}
<div class="flex-container">
<div class="content">
<div class="display-box">
<!-- <p>Please login to see this page.</p> -->
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>
<tr>
<!-- <td>{{ form.username.label_tag }}</td> -->
<td>{{ form.username }}</td>
</tr>
<tr>
<!-- <td>{{ form.password.label_tag }}</td> -->
<td>{{ form.password }}</td>
</tr>
</table>
<input id="login-button" class="button" type="submit" value="login">
<input type="hidden" name="next" value="{{ next }}">
</form>
{# Assumes you setup the password_reset view in your URLconf #}
<p id="lost-password-link">Lost password?</p>
</div>
</div>
</div>
{% endblock %}
I created a test html file and it also doesn't work: code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Words & Phrases</title>
</head>
<body>
<input type="text" id=“id_username”>
<script>
document.querySelector('#id_username').textContent = 'username';
</script>
</body>
You can try with this:
document.querySelector('input[name="id_username"]').value = 'Username';
<input type="text" name="id_username" id="id_username" placeholder="Your text">
Would like to point out that when you tried your queryselector. You used ".id_username", this selects a class that is called that, not the id.
You can try to store the selected element in a variable then, run the innerHTML/textcontent.
const stubbornInput = document.getElementById("id_username");
stubbornInput.innerHTML = 'Whatever you want';
Ive had cases where this worked but, going straight for the thing didnt. Not sure if it helps or why it worked for me before but, worth a shot :)
your text input has the ID username, in your javascript it says id_username try this input and the javascript.
document.getElementById("username").value = "your_value_here";
<input type="text" name="username" id="username">
If that doesn't work, try using JQuery.
$("input[name=username]").val("hello_world")
ok below is the correct answer:
my main js file was causing an issue which is why it didn't work for me earlier. After i created a empty js file for this purpose it worked.
document.querySelector('#id_username').value = 'username' ;
document.querySelector('#id_username').addEventListener('click', function () {
document.querySelector('#id_username').value = '';
})
Found an easier was to do this:
document.querySelector('#id_username').setAttribute('placeholder', 'Username');
Hi I am trying to create a printable page from data send by a form in octobercms
I have created a plugin component which I have called PrintPageForm
<?php namespace Acme\PrintPage\Components;
use Cms\Classes\ComponentBase;
use Input;
class PrintPageForm extends ComponentBase
{
public function componentDetails()
{
// TODO: Implement componentDetails() method.
return
[
'name' => 'Print Page Form',
'description' => 'Detail page print form'
];
}
public function onHandleForm()
{
$var =
[
'overview' => Input::get('print_overview'),
'photos' => Input::get('print_photos')
];
I have this in the default htm file
<form action="/print" data-request-data="printpageform::onHandleForm" data-request-validate data-request-flash accept-charset="utf-8" class="form ajax-form">
<h3 class="sub-heading">Print Details</h3>
<p>To build a printer friendly formatted page, please select from the options shown below:</p>
<ul class="print-section">
<li>
<input type="checkbox" class="checkbox-input" value="1" name="print_overview" id="print_overview">
<label class="checkbox-label period" for="print_overview">Overview: Summary and key features alongside a photo of the property.</label>
</li>
<li>
<input type="checkbox" class="checkbox-input" value="1" name="print_photos" id="print_photos">
<label class="checkbox-label period" for="print_photos">Photos: Photo gallery of the property.</label>
</li>
</ul>
<input type="hidden" name="print" value="1">
<button class="btn button-large one-third palm-one-whole" type="submit" rel="print" >Print</button>
</form>
I am trying to access the value of print_overview and print_photo values in my print view page but can not figure out how to access these values I can see these values being passed in Debugbar as follows "request_query
array:2 [ "print_overview" => "1" "print" => "1" ]" and in my view file I have
{%if "print_overview" == "1" %}
{{ 'checked' }}
{% else %}
{{ 'Not Checked' }}
{% endif %}
but it does seem to matter what the value of print_overview is the page only echos out Not Checked I'm in a rut that I can't figure out any thoughts would be gratefully accepted.
Couple of pointers. When rendering a form in Twig, you should use either the {{ form_open() }} or {{ form_ajax() }} tags
Secondly, you can access the request data via the post() function in your component class; and you pass it to your view (the component partial) through the page property. So, your handler would like something like:
public function onHandleForm()
{
// Pass the variables to the view renderer
$this->page['print_overview'] = (bool) post('print_overview');
$this->page['print'] = (bool) post('print');
// Return a partial response http://octobercms.com/docs/ajax/update-partials#pushing-updates
return ['#view-response-element' => $this->makePartial('#response')];
}
While your response.htm partial file would look something like this:
{% if print_overview %}
"checked"
{% else %}
"not checked"
{% endif %}
As a note, if you are using the {% macro %} tags, these do not have access to the local scope of the partial file, i.e. they do not have access to the variables provided to the view. Any evaluation done within {% macro %} tags needs to be based on variables passed to it.
The best strategy for printing I find is to use JavaScript:
<!-- Link to print -->
<p>Print this invoice</p>
<!-- Invoice printer -->
<script type="text/template" id="invoiceTemplateContents">
Printable contents go in here
</script>
<!-- Script -->
<script>
function printInvoice() {
var printWindow = window.open('','','left=0,top=0,width=950,height=500,toolbar=0,scrollbars=0,status=0')
printWindow.document.write($('#invoiceTemplateContents').html())
printWindow.document.close()
printWindow.focus()
printWindow.print()
printWindow.close()
}
</script>
So I am new to Django and a complete novice at JavaScript. I am trying to create a view which renders multiple forms dynamically using JavaScript. Below are two forms that I have created.
class CreateTestForm(forms.ModelForm):
class Meta:
model = Test
fields = ['name', 'test_group', 'description', 'query_text', 'failure_condition', 'status']
def getKey(self):
return "create_test_form"
class VC1Form(CreateTestForm):
expected_relation = forms.ChoiceField(choices = [('<','<'), ('>','>'), ('=','='), ('<=','<='), ('>=','>='), ('!=','!=')], required = True, label = 'Expected Relation: ')
num_rows = forms.IntegerField()
def getKey(self):
return "vc1_form"
In addition, I have the following view
def create_test(request):
context = {
'all_validation_classes': ValidationClass.objects.all()
}
for form in [CreateTestForm, VC1Form]:
if request.method == 'POST':
f=form(request.POST)
if (f.is_valid()):
return HttpResponseRedirect('/test_created/')
else:
return HttpResponseRedirect('/test_not_created/')
else:
f = form()
context[f.getKey()] = f
return render(request, 'create_test.html', context)
And template:
<form action="/tests/create/" method="post">
{% csrf_token %}
{{create_test_form.as_ul}} <br><br>
<select id="validation_classes_id" name="all_validation_classes" onchange="showForm()">
<option value="%">Choose the validation class</option>
{% for val_class in all_validation_classes %}
<option value="{{ val_class.id }}">{{ val_class.id}} {{val_class.name }}</option>
{% endfor %}
</select>
<br><br>
<script>
function showForm(){
var x = document.getElementById("validation_class_id").value;
}
</script>
<input type="submit" value="Submit" />
I am trying to get to a point, where, when the user selects something from the dropdown (validation_classes_id), the view will render the form corresponding to that selection. I have currently included only one additional form VC1Form here but I have written different forms corresponding to each option in the drop down.
I have tried a few things but nothing has worked yet and any help would be appreciated!
Try something this:
document.getElementById('form').querySelectorAll("label").forEach( e =>
{e.prepend(document.createElement("br"));});
Even better would be:
<form id="form" action="login_view" method="post">
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="register">
I'm trying to replace a 'reply' button with a form in my Django app.
Here's my Javascript code:
$(document).on('click', '.comment-reply-link', function(e) {
$(this).replaceWith("<form method='post'>{% csrf_token %}<div class='form-group'><label for='comment'>Comment:</label><textarea class='form-control' id='comment' rows='5' maxlength='300' minlength='1' name='comment' placeholder='Tell us how you loved this product :D'></textarea></div><button type='submit' name='post_comment' value='True'>Comment</button></form>");});
// The replacing line should contain no whitespace.
// Otherwise it will raise Uncaught SyntaxError: Unexpected token ILLEGAL
I get the form element but the problem is that {% csrf_token %} is processed as just unicode in replaceWith(). {% csrf_token %} is necessary in Django to submit a form. Any kind of help and advice will be thankful :)
Edit:
I assume that {% %} means that Django needs to be involved to retrieve the right value. So I thought I should render an html page with form and update that form with 'reply' button. Here's my logic.
view.html
<div class="reply">
<a class='comment-reply-link' href='{% url "rango:reply_form" %}'aria-label='Reply to Araujo'>Reply</a>
</div>
reply.js
function ajax_get_update(item){
$.get(url, function(results){
//get the parts of the result you want to update. Just select the needed parts of the response
// var reply_form = $("#reply_form", results);
var reply_form = $(".head", results);
console.log(reply_form);
//console.log(results);
//update the ajax_table_result with the return value
$(item).html(reply_form);
}, "html");
}
$(document).on('click', '.reply', function(e) {
console.log("Debuggin...");
e.preventDefault();
url = ($( '.comment-reply-link' )[0].href);
console.log(url);
ajax_get_update(this);
});
reply_form.html
<!DOCTYPE html>
... code omitted ....
<form id="reply_form" method="post">
{% csrf_token %}
<div class="form-group">
<label for="comment">Reply:</label>
<textarea class="form-control" id="comment" rows="5" maxlength="300" minlength="1" name="comment" placeholder="Tell us how you loved this product :D"></textarea>
</div>
<button type="submit" name="post_comment" value="True">Reply</button>
</form>
</body>
</html>
When I click the reply button, the button disappears but nothing updates. The html page variable results gets the correct html page data but it seems like
$(item).html(reply_form);
is not working right. Because when I do
$(item).html('<p>button disappears</p>');
the paragraph will appear. Any thoughts?
To use django template language in javascript you should encapsulate your code in a Verbatim tag.
example :
{% verbatim %}
var hello = {% if some_condition %} 'World' {% else %} 'foobar' {% endif %};
{% endverbatim %}
From the docs :
Stops the template engine from rendering the contents of this block tag.
A common use is to allow a JavaScript template layer that collides with Django’s syntax
In your case :
<script>
{% verbatim %}
$(document).on('click', '.comment-reply-link', function(e) {
$(this).replaceWith("<form method='post'> {% csrf_token %} </form>")
};
{% endverbatim %}
</script>