Post JSON data using Angular.js - python

This is my first crack at Angular. I'm posting JSON data to an html page using Angular.js. I know I'm missing something but can't seem to get it working. Below is the html. I have a python script posting to the same URL below.
<!doctype html>
<html lang="en" ng-app id="ng-app">
<head>
<title>File Analysis</title>
<script src="js/angular.js"></script>
<script>
var myApp = angular.module('fileAnalysis', []);
myapp.controller('PostsCtrlAjax', function($scope, $http)
{
$http({method: 'POST', url: 'http://test.com'}).success(function(data)
{$scope.posts = data;}) // response data
});
</script>
</head>
<body>
<h1>You should begin to see new files being analyzed!</h1>
<div id="ng-app" ng-app ng-controller="PostsCtrlAjax">
<div ng-repeat="post in posts" >
<h2>
<a href='{{post.url}}'>{{post.title}}</a>
</h2>
<td>
{{post.filename}}
</td>
</div>
</body>
</html>

Related

My Tamil letters are not displaying in Pdf file in Django

views.py
def pdf(request,songsheetname):
username=request.user.username
printsong=Songsprintform.objects.all().filter(username=username,removesong='0',
addsheetstatus='0',songsheetname=songsheetname,songprintstatus='1')
countsong=Songsprintform.objects.all().filter(username=username,removesong='0',
addsheetstatus='0',songsheetname=songsheetname,songprintstatus='1').count()
songid = []
for i in printsong:
songid.append(i.songprintid)
recentsongs=SongList.objects.all().filter(id__in=songid)
template_path = 'pdf.html'
context = {'recentsongs':recentsongs}
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename="songs.pdf"'
template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(html, dest=response)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
django template
<html>
<head>
<title>Page Title</title>
<meta charset="utf-8">
<style>
div {
column-count: 2;
column-width: 300px;
}
</style>
</head>
<body>
<div class="col-md-6">
{% for i in recentsongs %}
<p class="float-left">{{i.body |linebreaks}}</p>
{% endfor %}
</div>
</div>
</body>
</html>
This is my code...
Here I'm converting my Django template(html) page into pdf. All are Working fine but here my content are in Tamil. But here it displays as an Square box instead of Tamil Letters .whenever my click my button on see that pdf file it always shown as an square box. I don't Know why.Please help me...
Maybe the font you're using in the PDF does not support Tamil characters. Try changing to a font that supports them.
<html>
<head>
<style>
#font-face {
font-family: 'TamilFont';
src: url('/path/to/font.ttf') format('truetype');
}
body {
font-family: 'TamilFont';
}
</style>
</head>
<body>
<div class="col-md-6">
{% for i in recentsongs %}
<p class="float-left">{{i.body |linebreaks}}</p>
{% endfor %}
</div>
</div>
</body>
</html>
In your django python file, embed a font that supports Tamil characters. This way, when you convert it, the PDF software will recognize the font you want to use.

The value I got from the jQuery is NoneType in django

I want to implement a function that updates the graph and displays the number of updates when the button is pressed.
However, when I try to get the parameter in view.py using jQuery, it returns NoneType instead of the intended value. What is the problem?
Also, I don't know if this is related, but when I use console.log() in a jQuery function, there is no output on the console of the browser developer tools. This doesn't seem to have anything to do with the error-only mode or the filter I entered in Console.
The error is
TypeError at /graph/update_graph
int() argument must be a string, a bytes-like object or a number, not 'NoneType'
Thank you.
Here is the code
views.py
from xml.etree.ElementInclude import include
from django.shortcuts import render
from django.http import JsonResponse
from . import graphdata
def index(request):
fig = graphdata.get_scatter_figure()
plot_fig = fig.to_html(fig, include_plotlyjs=False)
return render(request, 'graph/index.html', {'graph':plot_fig})
def update_graph(request):
graph = graphdata.get_scatter_figure()
grahp_html = graph.to_html(graph, include_plotlyjs=False)
cnt = int(request.POST.get('count')) # <-- This is the error point
cnt += 1
data = {
"graph": grahp_html,
"count": cnt,
}
return JsonResponse(data)
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<!-- plotly JS Files -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
</head>
<body>
<div id="update-num">0</div>
<div id="update-text">update</div>
<form id="graph-update-form" action="{% url 'graph:update_graph' %}" method="POST">
{% csrf_token %}
<button type="submit" id="upadate-bt">update</button>
</form>
<div class="graph" id="scatter-graph">{{ graph| safe }}</div>
<!-- jquery script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#update-graph-from").on("submit", function(e){
e.preventDefault();
// These outputs will not be displayed in the console
console.log('hello');
console.log($("#update-num").text());
$.ajax(
{
url: "{% url 'graph:update_graph' %}",
type: "POST",
data: {
count: $("#update-num").text(),
},
dataType: "json",
}
)
.done(function(response){
$("#update-num").remove();
$("#update-num").prepend(response.count);
});
});
</script>
</body>
</html>
urls.py
from django.urls import path
from . import views
app_name = "graph"
urlpatterns = [
path('', views.index, name='index'),
path('update_graph', views.update_graph, name='update_graph'),
]
You have form with id="graph-update-form" and you are submitting the form with id="update-graph-from". Also since you already set url in your ajax you don't need your action="{% url 'graph:update_graph' %}" and method="POST" in your form. Also you can directly set your ajax response vale you don't need to remove the element so you don't have to prepend. Change your index.html as
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<!-- plotly JS Files -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
</head>
<body>
<div id="update-num">0</div>
<div id="update-text">update</div>
<form id="graph-update-form">
{% csrf_token %}
<button type="submit" id="upadate-bt">update</button>
</form>
<div class="graph" id="scatter-graph">{{ graph| safe }}</div>
<!-- jquery script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#graph-update-form").on("submit", function (e) {
e.preventDefault();
// These outputs will not be displayed in the console
console.log('hello');
console.log($("#update-num").text());
$.ajax({
url: "{% url 'update_graph' %}",
type: "POST",
'headers': {
'X-CSRFToken': $('#graph-update-form').find('input[name="csrfmiddlewaretoken"]').val()
},
data: {
count: $("#update-num").text(),
},
dataType: "json",
})
.done(function (response) {
$("#update-num").text(response.count);
});
});

Using Vue.js and Flask together

I had code that worked perfectly fine, then I wanted to use flask, so I copied it into a flask app directory. The html code is below:
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
</head>
<body>
<div id="app" class="container">
<div class="row">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item" v-for="tab in tabs" v-bind:class="tab.active">
{{ tab.name }}
</li>
</ul>
</div>
</nav>
</div>
<div class="row">
<div class="col">
<hr class="navbarDivide">
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="/static/js/challenges.js"></script>
</body>
</html>
When I remove the stuff for Vue, it works perfectly fine (when I remove the v-for, v-bind, and {{ tab.name }}. However, when I add it, it gives me a 500 error. I'm doing all of this using flask. Flask code below:
from flask import Flask, render_template
app = Flask(__name__)
application = app
#app.route('/base')
def index():
return render_template('base.html')
if __name__ == '__main__':
app.run(debug=True)
The javascript code just has the required stuff for Vue.js (the object with the data). The javascript code is below:
var app = new Vue({
el: '#app',
data: {
tabs: [
{ name: "Home", active: "" },
{ name: "Challenges", active: "active" },
{ name: "Scoreboard", active: "" },
{ name: "About", active: "" }
]
}
});
Update:
After a little more debugging, I think I may have figured out the problem. When I comment out all the stuff, and add console.log("it works"); to my javascript code, nothing happens. That probably means the javascript code isn't connecting to the html, but how can I solve that?
I found the solution. I was manually putting the url of the javascript
<script src="/static/js/challenges.js"></script>
What I had to do to fix it was use url_for
<script src="{{ url_for('static', filename='js/challenges.js') }}"></script>
Probably something a lot of people that have used flask before know, but I'm new to this.

python file not providing output in atom using angular

learning how to use angular and python on atom text editor
this is my angular code in index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
{{myData}}
<!-- <ul>
<li ng-repeat="x in myData">
{{x.name}},{{x.age}}
</li>
</ul> -->
</div>
</body>
</html>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get('test.py').then(function(response) {
$scope.myData = response.data;
});
});
</script>
and the python code is as below in test.py:
import json
message = "Hello World"
#test = [{'name':'sample1','age':'24'},{'name':'sample2','age':'25'}]
print json.dumps(message)
the commented code is what i really want to do, but i am not able to get the simple code work either.
when i run the code on live server, this is the output i see on the page http://127.0.0.1:3000/index.html:
import json message = "Hello World" #test = [{'name':'sample1','age':'24'},{'name':'sample2','age':'25'}] print json.dumps(message)

Vue app doesn't load when served through Python Flask server

I have a simple "hello world" VueJS app I'm trying to get working:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
Message: {{ message }}
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
message: "Hello, world"
}
});
</script>
</body>
</html>
When I load this file in the browser, off my local disk (ie: file:///home/user/vue-project/index.html), it loads and "Hello, world" is displayed.
However, if I try to take the same file and serve it through the python flask development server, or through gunicorn, {{message}} renders blank.
Does anyone know what might be causing that to happen?
flask renders its variables with jinja2 which uses {{ variable }} as its parsing delimiter
render("mytemplate.html",message="Hello") would replace all {{ message }} blocks with "Hello" before any javascript is handled ... since you dont define message it is simply an empty string... you will need to configure vue to use alternative delimiters (I use [[ message ]])
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
Message: [[ message ]]
</div>
<script>
var vm = new Vue({
el: "#app",
delimiters : ['[[', ']]'],
data: {
message: "Hello, world"
}
});
</script>
</body>
</html>

Categories