Call a python function using HTML/Django - python

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.

Related

Calling value from ajax to Django views

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)

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)

Ajax request not fired in django

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!

Implementing Typeahead on django

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?

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.

Categories

Resources