Implementing Typeahead on django - python

I'm implementing typeahead for the first time and I'm doing something wrong in passing the URL here. This is my typeahead:
$(document).ready(function(){
var getIsbn = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/update/?q=%QUERY",
wildcard: '%QUERY'
}
});
$('#remote .typeahead').typeahead(null, {
name: 'isbn',
display: 'value',
source: getIsbn
});
});
This is my URL in urls.py:
url(r'^update/(?P<id>[0-9]+)/$', views.update, name='update'),
When I open network panel Page not found is being displayed.
Any suggestion how to make this work?

Related

Django ServiceWorker not in scope

Thanks for your time.
i got a Django web app and am trying to set a PWA for it.
I've been seting the files (sw.js, manifest.json, install_sw.html) through urls with TemplateView class:
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('config/', include('config.urls')),
path('products/', include('products.urls')),
path('cart/', include('cart.urls')),
path('accounts/', include('allauth.urls')),
path('home/', home_view, name='home'),
path('sw.js/', (TemplateView.as_view(template_name="admin/sw.js", content_type='application/javascript', )), name='sw.js'),
path('manifest.json/', (TemplateView.as_view(template_name="admin/manifest.json", content_type='application/json', )), name='manifestjson'),
path('install_sw/', (TemplateView.as_view(template_name="admin/install_sw.html", content_type='text/html', )), name='install_sw'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
although i keep getting this error:
no matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest
and even with the serviceworker being found and his code running, i don't think its getting installed.
Lighthouse told me so, and when i leave the page the service worker ain't in the list anymore, so im not able to run it offline because the cache gets deleted.
files under:
sw.js:
{
const cacheName = 'cache-v1';
const resourcesToPrecache = [
"{% url 'sw.js' %}",
"{% url 'home' %}",
"{% url 'install_sw' %}"
];
self.addEventListener('install', function (event) {
console.log('sw install event!');
event.waitUntil(
caches.open(cacheName)
.then(function (cache) {
console.log('cache added')
return cache.addAll(resourcesToPrecache);
}
)
);
});
self.addEventListener('fetch', function (event) {
console.log(event.request.url);
event.respondWith(
caches.match(event.request).then(function (response) {
return response || fetch(event.request);
})
);
});
};
console.log('ok')
manifest.json
{
"short_name": "Mega",
"name": "MegaMagazine",
"scope": "/",
"icons": [
{
"src": "/static/m1.png",
"type": "image/png",
"sizes": "144x144"
}
],
"start_url": "/",
"background_color": "#3367D6",
"display": "standalone",
"theme_color": "#3367D6",
"prefer_related_applications": false
}
install_sw.html
<!doctype html>
<head>
<link rel="manifest" href="{% url 'manifestjson' %}">
</head>
<title>installing service worker</title>
<body>
<img src="/static/m1.png" alt="">
<script type='text/javascript'>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register("{% url 'sw.js' %}").then(function (registration) {
console.log('Service worker registrado com sucesso:', registration, registration.scope);
}).catch(function (error) {
console.log('Falha ao Registrar o Service Worker:', error);
});
} else {
console.log('Service workers não suportado!');
}
</script>
</body>
files
Your Project must be serve over localhost:[8000] or HTTPS.
If you serve it on local network like 192.168.43.101 you should change it to localhost or install SSL crt. on it.
Service workers require a Secure Context.
(MDN page, Chromium page).
The value of window.isSecureContext indicates whether
[SecureContext] features are visible or hidden. (This is true on a
file:// URL and the serviceWorker API will be visible, but it won't
work, of course.)

Get User Details from database in Django

I am working in site which display the details of a contact registered in my app, the error I have is when retrieving the data does not show and cannot find the Ajax request, any help would be appreciated
urls.py
from django.urls import path
from app_2 import views as app2
urlpatterns = [
#app_2
path('user', app2.userPanel),
path('get_user_info', app2.getUserInfo, name = 'get_user_info'),
]
Script in user.html
<script type="text/javascript">
$(document).ready(function(){
$("#users").change(function(e){
e.preventDefault();
var username = $(this).val();
var data = {username};
$.ajax({
type : 'GET',
url : "{% url 'get_user_inf' %}",
data : data,
success : function(response){
$("#user_info table tbody").html(`<tr>
<td>${response.user_info.first_name || "-"}</td>
<td>${response.user_info.last_name || "-"}</td>
<td>${response.user_info.email || "-"}</td>
<td>${response.user_info.is_active}</td>
<td>${response.user_info.joined}</td>
</tr>`)
},
error : function(response){
console.log(response)
}
})
})
})
</script>
You should add Ajax in your urlpatterns to specify what are you requesting:
urlpatterns = [
#app_2
path('user', app2.userPanel),
path('Ajax/get_user_info', app2.getUserInfo, name = 'get_user_info'),
]
and also there is an error in your code:
type : 'GET',
url : "{% url 'get_user_info' %}",
data : data,
success : function(response)

Call a python function using HTML/Django

I have a camera Speed Dome Intelbras VIP 5220 SD IR that I can move its position (PTZ function) using python code. However, I want to move its position using a button on the Webpage. I create a webpage using Django, so I want to click on the button and I want my camera to move after that, but I do not know how to call my python function using Django. I found some keywords like Django Channels, Ajax and WebSockets, but everything looks very complicated.
To do this I did this so far:
HTML:
<script>
$(document).ready(function(){
$("button").click(function(){
//alert("Botao foi clicado");
$.ajax({
type: "POST",
url: "/ajax_move_camera/",
data:{
"var1":"val1"
},
dataType: 'json',
sucess: function(data){
alert("Sucess");
},
error: function(data){
alert("Error")
}
})
});
});
</script>
VIEWS.py
def ajax_move_camera(request):
x=10
data={}
return JsonResponse(data)
URL.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.ajax_move_camera, name='ajax_move_camera')
]
A rough draft on how you can approach this
your_template.html
<html>
... stuff ...
<button id="camera_move_btn">Move Camera</button>
... stuff ...
<script>
function call_this_function_on_btn_click() {
$.ajax({
type: "POST",
url: "/ajax_move_camera/",
data: {
"var1": "val1"
"csrfmiddlewaretoken", "{{ csrf_token }}"
},
dataType: 'json',
success: function(data) {
... something comes back ...
}
})
}
</script>
views.py
def ajax_move_camera(request):
... do something ...
data = {}
return JsonResponse(data)
you will have to match the ajax url to the view method in your url.py file and remember to include Jquery as I used their ajax method.
If you don't want to add Jquery you can look into XMLHttpRequest which will do the request.

ajax post returns 404 for url in django 1.10

Im trying to post a simple ajax to 'signup' function in django but keep getting 404, I think it has to do with my url dispatcher and I need some help please..
my ajax looks like this:
$('#signupBtn').click(function() {
$.ajax({
type: 'POST',
url : '/signup',
dataType: "json",
data : {
userId : $('#signupEmail').val(),
userPassword : $('#signupPassword').val()
},
beforeSend: function() {
$('#signupBtn').hide();
},
error: function(xhr,errmsg,err) {
$('#signupBtn').show();
$('#signupEmail').val("");
$('#signupPassword').val("");
alert(xhr.status);
},
success : function(json) {
$('#signupBtn').show();
$('#signupEmail').val("");
$('#signupPassword').val("");
alert(json['u']);
}
});
return false;});
my views.py lookes like this:
def signup(request):
userid = request.POST.get('userId')
userpass = request.POST.get('userPassword')
data = { 'u' : userid, 'p' : userpass}
return JsonResponse(data)
and my app urls lookes like this:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^signup$', views.signup, name='signup'),]
what is my problem? and how do i fix it?
thanks.
Two things could be going wrong.
Missing CSRF token in API call. https://docs.djangoproject.com/en/1.11/ref/csrf/
Not properly serialized data. You need to use data=JSON.stringify({dictionary});
SOLVED!
should have indid put an extra / in the end.

How to recognise urls starting with anchor(#) in urls.py file in django?

I have starting building my application in angularJS and django, and after creating a login page, I am trying to redirect my application to a new url after successful login. I am using $location variable to redirect my page. Here is my code:
$scope.login = function() {
$http({
method: 'POST',
data: {
username: $scope.username,
password: $scope.password
},
url: '/pos/login_authentication/'
}).then(function successCallback(response) {
user = response.data
console.log(response.data)
if (user.is_active) {
$location.url("dashboard")
}
}, function errorCallback(response) {
console.log('errorCallback')
});
}
My initial url was http://localhost:8000/pos/, and after hitting the log in button, the above function calls, and I am redirected to http://localhost:8000/pos/#/dashboard. But I am unable to catch this url in my regex pattern in urls.py file:
My project urls.py file:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^pos/', include('pos.urls')),
url(r'^admin/', admin.site.urls),
]
And my pos application's urls.py file:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login_authentication/$', views.login_authentication, name='login_authentication'),
url(r'^#/dashboard/$', views.dashboard, name='dashboard')
]
Using this, I am getting the same login page on visiting this http://localhost:8000/pos/#/dashboard link. This means that in my urls.py file of my pos application, it is mapping my http://localhost:8000/pos/#/dashboard to first object of urlpatterns:url(r'^$', views.index, name='index'). How do I make python differentiate between both the links?
You have some major misunderstanding about and anchor in url. The anchor is called officially Fragment identifier, it's not part of the main url, so if you have # when you visit an url like http://localhost:8000/pos/#/dashboard, your browser would treat the remaining #/dashboard as the anchor in page that http://localhost:8000/pos/ renders. You shouldn't be even using it in your urls.py definition. Please read the link above more carefully about the usage of an anchor.
Using help from this answer, I figured a good redirection method through angular which doesn't append any anchor tag using $window:
$scope.login = function() {
$http({
method: 'POST',
data: {
username: $scope.username,
password: $scope.password
},
url: '/pos/login_authentication/'
}).then(function successCallback(response) {
user = response.data
console.log(response.data)
if (user.is_active) {
$window.location.href = '/pos/dashboard';
}
}, function errorCallback(response) {
console.log('errorCallback')
});
}

Categories

Resources