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.)
Related
I want to send a JsonResponse of a queryset from Django views to JQuery but I am not getting any data from the JQuery side.
This is my views file add_field_views.py :
from django.http import JsonResponse
def drop_down_requests(request):
text = request.POST['text']
print("---->", text)
from captiq.financing_settings.models import ChoiceGroup
response = ChoiceGroup.objects.get(slug="Ja/Nein")
output = JsonResponse(response,safe=False)
print("output -", output)
return output
this is where I declared the URL in urls.py inorder for the Jquery to GET the data from the views :
urlpatterns = [
path('my-ajax-test/', add_field_views.drop_down_requests, name='ajax-test-view'),
]
project urls.py:
frontend_urls = []
for module_name, module_data in FRONTEND_MODULES.items():
frontend_urls.append(re_path(
module_data['url'],
XFrameSameOriginView.as_view(template_name=module_data['view']),
name=module_name))
urlpatterns = i18n_patterns(
path('admin/', admin_site.urls),
path('admin/log_viewer/', include(
('log_viewer.urls', 'log-viewer'), namespace='log-viewer')),
path('admin/docs/', include('docs.urls')),
path('_nested_admin/', include('nested_admin.urls')),
path('accounts/', include(
('accounts.urls', 'accounts'), namespace='accounts')),
path('api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
)
api_v1_patterns = [
path('financing/', include(
('financing.urls', 'financing'), namespace='financing')),
path('financing-settings/', include(
('financing_settings.urls', 'financing_settings'),
namespace='financing_settings')),
path('partners/', include(
('partners.urls', 'partners'), namespace='partners')),
path('accounts/', include(
('accounts.urls', 'accounts'), namespace='accounts')),
path('customers/', include(
('customers.urls', 'customers'), namespace='customers')),
]
urlpatterns += [
path('api/v1/', include((api_v1_patterns, 'api'), namespace='api')),
path('', RedirectView.as_view(url='loan-application/auth')),
path('notifications/', include(
'notifications.urls', namespace='notifications')),
] + frontend_urls
if settings.ENABLE_ROSETTA:
urlpatterns += i18n_patterns(
path('admin/rosetta/', include('rosetta.urls')),
)
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
then is my JQuery which is waiting for the queryset data or JSON data :
window.addEventListener('load', function () {
(function ($) {
"use strict";
$(document).ready(function () {
$("#id_depending_field").change(function (event) {
console.log("am here man");
const valueSelected = this.value;
$.ajax({
type: "POST",
url: 'my-ajax-test/',
data: {
csrfmiddlewaretoken:
document.getElementsByName('csrfmiddlewaretoken')[0].value,
text: valueSelected
},
success: function callback(response) {
console.log("____________", response)
}
});
})
});
})(django.jQuery);
});
With the code above am not able to get JSON data in JQuery, Instead I get a weird HTML output below :
<link rel="stylesheet" type="text/css" href="/static/css/notifications.css">
.
What am I doing wrong here ?
when you use relative path it is easy to lead your urls to wrong place. at your page your ajax will call for /en/admin/financing_settings/field/add/my-ajax-test/.
you can save exact url on your html page with data-* attribute.
In your example add data-ajax_url attribute to your #id_depending_field (or any other element)
data-ajax_url="{% url "api:financing_settings:ajax-test-view" %}" - url must be like this as i understand your routing
and then in your ajax code instead of url: 'my-ajax-test/', use url: $(#id_depending_field).data('ajax_url')
this will always give you exact url from any page where you load your .js file. And later if you decide to refactor your project and change url path it will keep all changes for you without changing html or js code
Use absolute URL when sending AJAX request:
$.ajax({
type: "POST",
url: '/my-ajax-test/',
data: {
...
})
Apparently, you were sending it to /en/admin/financing_settings/field/add/my-ajax-test/ cause it was relative
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)
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.
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?
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')
});
}