Angularjs with Django using AJAX request - python

I sent a information by Post method until one views in Django and returned to the site. However, I'm not getting submit this information on the site.
File post3.html
<!DOCTYPE html>
<html ng-app>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
<script>
function ListDropdown($scope, $http){
$scope.ccvms={lista01:['1','3','5','7','9'],lista02:['2','4','6','8','10']}
$scope.send=function(x,y){
$http({
method:'POST',
url:'/escalar',
data:x+y,
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(c){
console.log(c)
})
}
}
</script>
</head>
<body>
<div ng-controller="ListDropdown">
<select ng-model="ccvm" ng-options="ccvm as ccvm for (ccvm, nums) in ccvms"></select>
<select ng-model="num" ng-disabled="!ccvm" ng-options="num for num in ccvms[ccvm]" ng-change="send(num, ccvm)"></select>
<h1 ng-model=c>
</div>
</body>
</html>
File views.py
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.http import HttpResponse
from django.shortcuts import render_to_response
def post3(request):
return render_to_response("post3.html")
#csrf_exempt
def escalando(z):
x=list(z.POST)
c=str(x[0])+"_retornou"
return HttpResponse(c)
File urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^post3/','bvmfconsulta.views.post3'),
url(r'^escalar','bvmfconsulta.views.escalando'),
)
Appears in the console.log(c) the information, for example "4lista02_retornou", however, I am not getting insert it on the site.

I resolved as follows:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
<script>
function ListDropdown($scope, $http){
$scope.ccvms={lista01:['1','3','5','7','9'],lista02:['2','4','6','8','10']}
$scope.resposta=""
$scope.send=function(x,y){
$http({
method:'POST',
url:'/escalar',
data:x+y,
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(c){
$scope.resposta=c
})
}
}
</script>
<h1 ng-bind="resposta"></h1>

Related

NoReverseMatch Error at "url" in Django while requesting AJAX url

I am trying to refresh the table data in my Django HTML page, without refreshing the whole page after every 10 seconds ... for which I am using AJAX in Django
This is the HTML Page I want to render -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>temp1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello there</h1>
<h1>{{info_data}}</h1>
<table id="_appendHere" class="table table-striped table-condensed">
<tr>
<th>Username</th>
<th>Email</th>
<th>Gender</th>
</tr>
{% for item in info_data %}
<tr><td>{{item.username}} - {{item.email}} - {{item.gender}}</td></tr>
{% endfor %}
</table>
</body>
<script>
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: {% url 'App1:temp' %}, // URL to your view that serves new info
})
}, 10000)
</script>
</html>
I have created a model inside an app called "App1" whose data I am passing to this table using this code -
from django.shortcuts import render
from App1.models import Info
# Create your views here.
def tempPage(request):
info_data=Info.objects.all()
context={"info_data":info_data}
return render(request,"App1/temp1.html",context)
This is the urls.py for App1 -
from django.contrib import admin
from django.urls import path,include
from App1 import views
app_name = 'App1'
urlpatterns = [
path('temp/', views.tempPage,name="tempPage"),
]
But I get this error on the URL http://localhost:8000/temp/ -
NoReverseMatch at /temp/
Reverse for 'temp' not found. 'temp' is not a valid view function or pattern name.
I am not sure where I'm going wrong
I even added a namespace for the App and included that in the url part of the AJAX request "App1:temp"
But that gives the same error
Project Structure -
Any help would be highly appreciable!! Thanks!!
You have typo error in your url change temp to tempPage
<script>
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: {% url 'App1:tempPage' %}, // URL to your view that serves new info
})
}, 10000)
</script>

Unable to send variable from views to html python

Am Unable to sent the temp_k variable from my views to index.html. I have made a request from weather API and trying to pass it to my html.
Please suggest how we are supposed to send the variable from views to template.
views.py
from django.template.loader import render_to_string
import requests
from django.shortcuts import render
from django.http import HttpResponse
def hello(request):
my_dict = {'insert_me': "From andu.py"}
return render(request, 'mywebapp/index.html', context=my_dict)
def temperature(request):
#zip=requests.form['zip']ss
r=requests.get('http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b6907d289e10d714a6e88b30761fae22')
json_object=r.json()
my_dict1={'temp_k' :json_object['main']['temp']}
return render(request,'mywebapp/index.html', context=my_dict1)
index.html
<!DOCTYPE html>
{% load staticfiles%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hey</title>
<link rel="stylesheet" href={% static "cs/style.css" %}/>
</head>
<body>
<h1>This is the Header</h1>
<img src="{% static "images/youownme.jpeg" %}" atl="Uh Oh">
<h2> Temperature:{{temp_k}}</h2>
</body>
</html>
I have tried your code and it works fine so you may want to check if you are rendering the right HTML files maybe, i've changed your code to make sure it's working and it is
my_dict1={'temp_k' :json_object['wind']['speed']}
sorry but I cant write a comment yet!
Use render like this :
return render(request,'mywebapp/index.html',{'context':my_dict})

routing with django and AngularJS

I new to AngularJS and trying to set up Django with AngularJs, however, I have some issues with handling the routing with those two frameworks. so far I've set up like below:
When I run http://localhost:8000/index.html it works and shows me the file, but when I run http://localhost:8000/test as I wrote in app.js it gives me standard Django 404 error.
What am I missing?
urls.py
urlpatterns = [
url(r'^index.html/$',
]
app.js
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/test", {
templateUrl : "index.html",
controller: "MainCtrl"
})
});
app.controller("MainCtrl", function ($scope) {
$scope.msg = "test";
});
index.html
{% load static %}
<html ng-app="myApp">
<head>
</head>
<body>
<div>
test
</div>
<script src="{% static 'js/general/angular.min.js' %}" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script type="text/javascript" src="{% static 'js/app.js' %}"></script>
</body>
</html>
You need to define the URL and it's corresponding views method.
In you urls.py
You need something like:
url(r'^test/$', views.test, name='test')
In views.py
def test(request):
return HttpResponse('You are looking at test')

Why did I get a blank page after using Django_ajax with django?

I'm a beginner in django, I follow the steps showed at GitHub, but I just got a blank page, here my code:
views.py
from django.shortcuts import render
from django_ajax.decorators import ajax
#ajax
def AjaxView(request):
return render(request, 'blogs/ajaxtest.html'`
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^ajax/', 'blogs.views.AjaxView', name='Ajax'))
ajaxtest.html
<head>
<script type="text/javascript" src="{% static '/blogs/django_ajax/js/jquery.ajax.min.js' %}"></script>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<title>Ajax Test</title>
</head>
<body>
<script type="text/javascript">
ajaxGet('/', function(content){
//onSuccess
alert(content);
})
</script>
</body>
You need to include jQuery before django_ajax or django_ajax won't work, it is a requirement.
Also your AjaxView function seems to be incomplete.

httpresponse not rendering the html page

I'm a newbie to Django and created a sample project with an app:
views.py
from django.http import HttpResponse,Http404
from django.contrib.auth.models import User
from django.template import Context
from django.template.loader import get_template
def main_page(request):
template = get_template('main_page.html')
variables = Context({
'head_title': u'Django Bookmarks',
'page_title': u'Welcome to Django Bookmarks',
'page_body': u'Where you can store and share bookmarks!'
})
output = template.render(variables)
print 'output',output
return HttpResponse(output)
urls.py
from django.conf.urls.defaults import patterns, include, url
from bookmarks.views import *
urlpatterns = patterns('',
(r'^$',main_page),
(r'^user/(\w+)/$',user_page),
#(r'login/$','django.contrib.auth.views.login')
)
main_page.html
<html>
<head>
<title>{{head_title}}</h1>
</head>
<body>
<h1>{{page_title}}</h1>
<p>{{page_body}}</p>
</body>
</html>
When I print the output variable, I see everything perfectly all right but when I run the server and point to the page, I see a blank page.
You are missing the closing tag </title>
Your template should look like this
<html>
<head>
<title>{{head_title}}</title>
</head>
<body>
<h1>{{page_title}}</h1>
<p>{{page_body}}</p>
</body>
</html>

Categories

Resources