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
Related
How can I send data ( the user_to_follow in this example ) to my views.py function ( follow ) to do some updates?
I'm trying to send the username from my JavaScript and then add the logged-in username to that username following list ( all done in my views.py function )
Views.py.
def follow(request, profile_to_follow):
try:
user_to_follow = User.objects.get(username=profile_to_follow)
user_to_following = Profile.objects.get(user=request.user.id)
except User.DoesNotExist:
return JsonResponse({"error": "Profile not found."}, status=404)
if request.method == "PUT":
user_to_following.following.add(user_to_follow)
return HttpResponse(status=204)
index.js
function follow_user(user_to_follow){
// How To send the user_to_follow to my views.py method.
// to add the current logged in user to the user_to_follow following list
console.log(user_to_follow)
}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
# API Routes
path("posts", views.compose_post, name="compose_post"),
path("posts/all_posts", views.show_posts, name="show_posts"),
path("posts/<int:post_id>", views.post, name="post"),
path("profile/<str:profile>", views.display_profile, name="profile"),
path("<str:profile_posts>/posts", views.display_profile_posts, name="profile_posts"),
path("follow/<str:user_to_follow>", views.follow, name="follow"),
]
The easiest method would be using an Ajax Query to send data from templates to your views.py
index.js
<script>
$(document).ready(function() {
function follow_user(user_to_follow){
$.ajax({
type: "PUT",
url: "{% url 'follow' user_to_follow %}",
data: {
user_data: user_to_follow,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function( data )
{
alert("Successful Added User to list");
}
});
});
});
</script>
views.py
def follow(request, profile_to_follow):
try:
user_to_follow = User.objects.get(username=profile_to_follow)
user_to_following = Profile.objects.get(user=request.user.id)
except User.DoesNotExist:
return JsonResponse({"error": "Profile not found."}, status=404)
if request.method == "PUT" and request.is_ajax():
user_to_following.following.add(user_to_follow)
return HttpResponse(status=204)
request.is_ajax()
This will return a boolean value based on whether the request is an AJAX call or not.
You can also refer to this documentation https://api.jquery.com/jQuery.ajax/#options
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.)
i have a problem, i think the ajax doesn't reach the matched view. This is the ajax I'm trying to send
$.ajax(
{
url : 'ajax/create_lobby/',
data: {
'creator' : data.message.creator,
'opponent' : data.message.opponent,
},
headers:{
"X-CSRFToken": csrftoken
},
dataType: 'json',
success: function (data){
alert("Sended ajax request");
}
}
)
where var csrftoken = $("[name=csrfmiddlewaretoken]").val();
The main urls.py contains this:
urlpatterns = [
path('chat/', include('chat.urls')),
path('admin/', admin.site.urls),
#this is what is not working
re_path(r'^ajax/create_lobby/$', quizViews.createLobby, name = "create_lobby"),
path("lobbies/", include('lobbies.urls')),
path("lobby/", include('quiz.urls')),
path('', include('accounts.urls')),
]
So i took care of matching urls more restrictive first.
This is the matched view by the url:
#csrf_exempt
def createLobby(request):
creator = request.GET.get("creator", None)
opponent = request.GET.get("opponent", None)
print(creator)
print(opponent)
data = {
'creator' : creator,
'opponent' : opponent
}
return JsonResponse(data)
This is the info i get in pycharm's console:
HTTP GET /lobbies/ajax/create_lobby/?creator=mihai&opponent=alexandru 200 [0.09, 127.0.0.1:56867]
If i try to send via POST method i get in console the next message but i don't understand why.
Forbidden (CSRF token missing or incorrect.): /lobbies/ajax/create_lobby/
The ajax seems to not be fired and i can't see the problem. Can you help me, i'm new to ajax. Thank you!
I have set up django to work in my local environment. I have a python function which takes two parameters and returns data in JSON format. This is set up in my views.py and urls.py as follows:
views.py :
from django.http import Http404, HttpResponse
from X import calculate
def calculate_X(request, para1, text):
#para1 is ignored on purpose
return HttpResponse(calculate(text))
urls.py :
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^calculate-X/(\d+)/([a-zA-Z0-9_ ]*$)',calculate_X),
url(r'^$', TemplateView.as_view(template_name='base.html')),
]
urlpatterns += staticfiles_urlpatterns()
In the base.html file I have a single button which should make the request to the calculate-x url as follows /calculate-X/1/stringdataexample
which would then create an alert() with the contents of the httpresponse ( JSON )
How can I make this request?
(There is another question asked here on SO however it uses request processors which do not relate to my question)
one way could be to trigger an ajax call when you click that button, and then process the response as you wish.
The button's html could be something like this:
<button onclick="processCalculation()">Calculate!</button>
Something like this function:
function processCalculation(){
var para1 = $("#params-container").val();
var text = $("#text-container").val();
$.ajax({
url: "/calculate-X/" + para1 + "/" + text,
data: {}
}).done(function (jsonResponse) {
alert(jsonResponse)
});
}
I hope this points you on the right direction, Best regards!
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')
});
}