typeahead autocomplete for Django - django

base.html
<html lang=en>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="/media/js/autocomplete.css">
<script type="text/javascript" src="/media/js/jquery-1.2.1.js"></script>
<script type="text/javascript" src="/media/js/dimensions.js"></script>
<script type="text/javascript" src="/media/js/autocomplete.js"></script>
{% block extra_css %}{% endblock extra_css %}
<title>{% block title %}books are social{% endblock title %}</title>
</head>
<body>
{% block body %}
{% endblock body %}
</body>
</html>
and the smaller template:
<script type="text/javascript" >
$(function(){
setAutoComplete("bookSearchField", "bookResults", "/lookup/?query=");
});
</script>
<label for="bookSearchField">Book: </label>
<input type="text" id="bookSearchField" name="bookSearchField">
urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('project.app.views',
(r'^/lookup/$', 'book_lookup'),
)
models.py
class Book(models.Model):
name = models.CharField(max_length=200)
views.py
from django.utils import simplejson
from django.http import HttpResponse
from project.app.models import Book
def book_lookup(request):
# Default return list
results = []
if request.method == "GET":
if request.GET.has_key(u'query'):
value = request.GET[u'query']
# Ignore queries shorter than length 3
if len(value) > 2:
model_results = Book.objects.filter(name__icontains=value)
results = [ {x.id :x.name,} for x in model_results ]
json = simplejson.dumps(results)
return HttpResponse(json, mimetype='application/json')
so is there any tutorial/solution to create bootstrap typeahead for elagent and responsive .
<input id="book_lookup" class="search-query typeahead" data-items="4" type="text"
placeholder="Select here....">
Edited:
<script type="text/javascript">
var typeahead_data = [];
function get_client_names() {
$.ajax({
url: "/lookup/?query=",
success: function (data) {
$.each(data, function (key, value) {
typeahead_data.push(value.toString());
});
// assign the array to my typeahead tag
$('.typeahead').typeahead({
source: typeahead_data,
});
}
});
}
$(function () {
get_client_names();
});
</script>
need something like
$("#book_lookup").tokenInput([{"id": 1, "name": "ddddd"},{"id": 2, "name": "ddffddd"}],{preventDuplicates: true,
hintText: "Type book name here...",
validateInputAjax: true,
validateInputObjectType: "book name",
validateInputNewObjectLink: function (value) {
$('#book_lookup').tokenInput(
'add', {'id': value, 'name': value});
return true;
},
validateInput: function (value) {
$.post("/lookup/", {validate_field_name: value},
function(data){
if (data.valid) {
$("#book_lookup").tokenInput('valid', value);
} else {
$("#book_lookup").tokenInput('invalid', value, 'is not a valid Book name');
};
});
}});
});
how to change data-source to book_lookup json view ?

I have used Bootstrap's typeahead before and what I did was create a method to get the dictionary via Ajax like this:
<script type="text/javascript">
var typeahead_data = [];
function get_client_names() {
$.ajax({
url: "/lookup",
success: function (data) {
$.each(data, function (key, value) {
typeahead_data.push(value.toString());
});
// assign the array to my typeahead tag
$('.typeahead').typeahead({
source: typeahead_data,
});
}
});
}
$(function () {
get_client_names();
});
</script>
The tag element is like this:
<input id="book_lookup" class="search-query typeahead" data-items="4" type="text"
placeholder="Select here....">
And basically the rest of your code is ok.
Note that here you're doing an ajax request (this requeires jquery) to the /lookup/ view which in turn returns a json object, that should look like this: [name1,name2,name3...]. You can test if the view is working ok by just accessing the view through the explorer like this: /lookup/ and if you see the dictionary displaying correctly there, the server side is ok.
Hope this works for you!

In Paulo's answer, he just has a static list of items to search from, that is why he calls the ajax on load, and gets the list and adds it to the source.
In your case, I think, you need to query whatever the user types, and send it to the server. This can be done by adding the function param in data-source, which gets 2 arguments, query and a callback.
Check here

Related

How can I pass a variable via jinja to a litelement?

I'm using flask to serve this html file. It is using jinja to display the provided data from flask. I can tell that the data is there, but I'm not sure how to pass it to my lit element.
<head>
<meta charset="utf-8">
<title>title</title>
<script type="module" src="{{ bundle }}"></script>
<script>
var data = {{ data|tojson }};
</script>
</head>
<body>
User: {{ data.user }}
<app-home .user="${data.user}" ></app-home>
</body>
</html>
The jinja code User: {{ data.user }}, works as expected.
But, in the litelement (AppHome), user is undefined.
I tried a few different variations on the formatting like .user="{{data.user}}", but I haven't been successful in passing the data to the litelement.
Edit to add lit code
import { html, LitElement, property, customElement } from 'lit-element/lit-element.js';
#customElement('app-home')
export class AppHome extends LitElement {
#property({type: String}) user?: string;
render() {
return html`
<p>user: ${this.user}</p>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'app-home': AppHome;
}
}
The litelement works as expected, and can even render the user if I fetch it separately.

Django Vuejs -- Using Axios - Issue in redering Data

I am trying to use VueJs inside my Django Framework ( Django as Backend) and Vuejs as Front-End. However, I am very new with axios, which I found more easier to use with VueJS Front-End. On integrating all togetherr, I didn't see anything coming up but I can see that my code is loop through the data using vueJS Developer Tools.
index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The greatest news app ever</title>
</head>
<body>
<div id="app">
<template v-for="post in posts">
<p> Hello - {{ post.title }}</p>
</template>
</div>
<script src="{% static 'vue/vue.js' %}"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="{% static 'vue/app.js' %}"></script>
</body>
</html>
app.js
new Vue({
el: '#app',
data: {
posts: []
},
methods:{
getPost: function(){
var self = this;
let url = "http://127.0.0.1:8000/api/allpost/";
axios.get(url).then((response) => {
this.posts = response.data
}, (error) => {
console.log(error);
});
}
},
mounted: function() {
this.getPost();
}
});
The Output of the code
{{ post.title }} has been the problem rendering the Data into Django Page, because Django also make use of this {{ }}. However, in a situation where someone is rendering the page with VueJS Server is doesn't apply. then, remember to add this:
delimiters: ['[[', ']]'],
<li v-for="post in posts" v-bind:key="post.id">
[[ post.title ]] <br/>
[[ post.body ]]
<hr/>
<li>
new Vue({
delimiters: ['[[', ']]'],
el: '#app',
data: {
posts: []
},
methods:{
getPost: function(){
var self = this;
let url = "http://127.0.0.1:8000/api/allpost/";
axios.get(url).then((response) => {
this.posts = response.data
}, (error) => {
console.log(error);
});
}
},
mounted: function() {
this.getPost();
}
});

Loading failed for the <script> with source “http://127.0.0.1:8000/static/js/bootstrap.min.js”

I'm getting the error "Loading failed for the with source “http://127.0.0.1:8000/static/js/bootstrap.min.js”." and my ajax is also not working. I want to delete a django form without refreshing my page
def client_delete(request, pk):
data = {'success': False}
client = Client.objects.get(pk=pk)
if request.method == 'GET':
try:
client.delete()
if client:
data['success']=True
else:
data['success'] = False
data['error'] = "unsuccessful!"
except Client.DoesNotExist:
return redirect('/NewApp/clientlist')
return JsonResponse(json.dumps(data))
In my client_list.py file,
{% block javascript %}
<script src="{% static '/js/app.js' %}"></script>
<script src="{% static '/js/jquery-3.2.1.js' %}"></script>
<script src="{% static '/js/bootstrap.min.js' %}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4 /jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.marquee#1.5.0 /jquery.marquee.min.js"></script>
{% endblock %}
<script>
document.getElementById("print").addEventListener("click", function() {
console.log("deleted")
alert('ok');
var id = $(this).attr('name');
$.ajax({
type:'GET',
url: 'NewApp/clientdelete' + id,
data:{
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function(data){
if(data.success == true){
alert("success");
}
}
});
return(false);
});
Try the path in the template without the leading "/" infront of js. It should look like {% static 'js/app.js' %} and make sure to use {% load static %} or {% load staticfiles %} based on your template.

How can Javascript or jQuery access my Django Models?

I have a little bit of jQuery on my page which needs to access one of my Django Models. Basically it's a form autocomplete, and it needs to look up values in my database.
I understand how to get values into a Django Template, but getting them into some Javascript code is confusing.
Is this possible? How can it be done?
Thank you.
This link has everything you need. The code is properly written and easy to understand. You can use the values of your model/table to be auto populated in the input field. Check from this link.
def get_Datas(request):
if request.is_ajax():
q = request.GET.get('term', '')
Datas = DataModel.objects.filter(short_name__icontains = q )[:20]
results = []
for Data in Datas:
Data_json = {}
Data_json['value'] = Data.short_name
results.append(Data_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
And use this in template,
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" />
<div class="ui-widget">
<label for="datas">datas: </label>
<input id="datas">
</div>
And the script would be:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script>
$(function() {
$("#datas").autocomplete({
source: "/get_Datas/",
minLength: 1,
});
});
</script>

url should not change on submitting a form

i have this Django application in which when user request for "localhost:8000/time/ ,it is shown html form input.html.
<head>
<!-- paste this in your footer -->
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(),
type: $(this).attr('POST'), // "post"
url: $(this).attr('/poi/'), // "/poi/"
success: function(response) {
// do something here
}
});
return false;
});
});
</script>
<!-- add jquery or it won't work -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form action="/poi/" method = "post">
<!---------
first name :<input type ="text" name ="fname">
last name:<input type ="text" name ="lname">
------>
enter a days :<input type ="text" name ="days">
<br>
<input type=submit name="submit" onclick="submit_function(); return false;">
</form>
</body>
when form is submitted user sees response.html page and URL is changed to "localhost:8000/poi/ is shown having
urls.py
urlpatterns = patterns('',
(r'^hello/$', hello),
('^time/$', current_datetime),
('^poi/$', next_datetime),
)
views.py
def current_datetime(request):
return render_to_response('input.html')
def next_datetime(request):
now = datetime.datetime.now()
now_day = now.day
now_month = now.month
now_year = now.year
return render_to_response('response.html', {'now_day': now_day, 'now_month'}}
now i have to do same thing but the url should not change from "localhost:8000/time/ to "localhost:8000/poi/
but it should be "localhost:8000/time/
how to accomplish that?
You have to use ajax to accomplish this
With jquery it would look something like
<form id="myForm"> ... </form> <!-- add an id to your form -->
<!-- paste this in your footer -->
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(),
type: $(this).attr('method'), // "post"
url: $(this).attr('action'), // "/poi/"
success: function(response) {
// do something here
}
});
return false;
});
});
</script>
<!-- add jquery or it won't work -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
and it should work out of the box
this is with an anonymous function, but you can put the code inside a named one and then add it to the button:
<input type="submit" onclick="submit_function(); return false;" />
it's basically the same