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!
Related
Im confused why it returns None when I print the value that comes from ajax, I used request.POST.get("ajaxvalue") to get the value from ajax requests but it didn't work, can anyone know what's the problem I encountered? it's very helpful for me.
views.py
#csrf_exempt
def updateStatus(request):
if request.method=="POST":
taskId = request.POST.get('id')
source = request.POST.get("sources")
target = request.POST.get('targets')
print(taskId);
print(source);
print(target);
return JsonResponse({'datas': 'test'})
html ajax
$.ajax({
data: {
id,
'sources':0,
'targets':1
},
url: "{% url 'updateStatus' %}",
type: 'POST',
cache: false,
contentType: false,
processData: false
})
.done(function(data){
console.log("success");
});
urls.py
urlpatterns = [
path('updateStatus/',views.updateStatus, name='updateStatus'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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.
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.
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')
});
}
When passing the X-CSRFToken header or sending csrfmiddlewaretoken in the POST data to my view, it completely skips the ajax handler and goes directly to the index/base view.
Javascript:
$.post("/action/register", {
name: $('#input_name').val(),
email: $('#input_email').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
}, function(data) {
var response;
try {
response = JSON.parse(data.toString());
} catch(e) {
response = {"status":"error", "message":"Please try again later, we're having some tech issues!"};
}
// ... process some stuff, the callback works which is good
View:
def handle_register(req):
''' Request handler pyfor registration, should return JSON for the AJAX request. '''
if req.is_ajax():
return validate_and_register(req)
else:
return HttpResponse('{"status":"error","message":"Invalid request."}')
urls.py:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^action/register$', 'views.handle_register', name='handle_register'),
url(r'^admin/', include(admin.site.urls)),
url(r'^.*$', 'views.handle_home', name='handle_home'),
)
When I don't pass the header, i get a 403 (CSRF_VERIFICATION_FAILED). When I pass the appropriate header (confirmed in multiple browsers) it skips the /action/register handler and goes directly to the "handle_home" view.
I'm stuck!
This could possible be due to a missing slash on your url
/action/register
Try adding a slash in url and in your javascript.
Another guess would be:
'views.handle_register'
is missing an app name?
A more safe was as well would be to use reverse urls:
from django.core.urlresolvers import reverse
url = reverse('appname.views.handle_register')
$.post(url, {}, func...
This was an issue with nginx. Per the django/nginx setup docs I found I was missing this in my nginx config:
fastcgi_split_path_info ^()(.*)$;