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.
Related
1. Background:
I am new to Flask, JavaScript or web development. I am currently trying to build an interface for a project of mine, which does extract the linear area of a curve. So far so good, my python code works: It reads data from an .csv or .xlsx file and returns the area, it's slope and plots for each sample. Now I am desperately trying to put them in some kind of user interface, so you can decide which ones to plot. I recognized image-picker (github.com/rvera/image-picker) as a suitable tool for the job, so I decided to implement it into my project. For this I started to build a simple test-page with the image-picker.
2. Problem
Unfortunately, I wasn't able to achieve this. Instead of seeing a list of the image names followed by the pictures, I can only get the list. I will add screenshots of the outcomes.
3. My Code
The project structure
Both, image-picker.css and image-picker.js are taken from the image-picker github
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="{{ url_for('static', filename = 'css/main.css') }}">
{% block head %} {% endblock %}
</head>
<body>
{% block body %} {% endblock %}
</body>
</html>
img_picker.html
{% extends 'base.html' %}
{% block head %}<title>Image Picker</title> {% endblock %}
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='image-picker.css') }}">
<script src="{{ url_for('static', filename='image-picker.js') }}" type="text/javascript"></script>
{% block body %}
<select multiple="multiple" class="image-picker show-html">
<option data-img-src='http://placekitten.com/220/200' value='1'>Cute Kitten 1</option>
<option data-img-src='http://placekitten.com/180/200' value='2'>Cute Kitten 2</option>
<option data-img-src='http://placekitten.com/130/200' value='3'>Cute Kitten 3</option>
<option data-img-src='http://placekitten.com/270/200' value='4'>Cute Kitten 4</option>
</select>
<script> $('.image-picker').imagepicker();
</script>
{% endblock %}
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('img_picker.html')
if __name__ == '__main__':
app.run()
main.css
body{
margin: 0;
font-family: sans-serif;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
How it looks
How it should look
(The website I took the example from: https://rvera.github.io/image-picker/)
If you need any more information, I will be glad to provide it. There has been another question regarding this problem before, but it wasn't solved.
Thanks for any help,
Carroll
I'm my django app I would like to load a static html page into a main template. This static html page is an email template. My goal is to edit this email in my main template. The email html page don't have a view in url.py. I don't use include in main template and I don't want to use iframe. The problem is that I would like to load ALL the html email tag (like
<html>
<head>
<body>
) but when I do the page's render this tag is deleted (or I don't see them in main template...). This is my code:
view.py
def my_view(request):
file_name = "/templates/path/emailtemplate.html"
htmlblock = render_to_string(file_name, {})
return render_to_response('main_template.html', {
'htmlblock': htmlblock,
},
context_instance = RequestContext(request))
main_template.html
<html>
<head>
....
<head>
<body>
<div id="content">
{{htmlblock}}
</div>
</body>
</html>
this is what I would like to have:
<html>
<head>
....
<head>
<body>
<div id="content">
<html>
<head>
....
</head>
<body>
...
</body>
</html>
</div>
</body>
</html>
Is this possible without iframe? Thanks a lot for your help.
EDIT
My goal is to have the
<html>
<head>
<body>
tag into
<div id="content">
where I load the email template.
My goal is to edit this email in my main template.
You can read the template into string by
with open('/templates/path/emailtemplate.html', 'r') as content_file:
content = content_file.read()
You can use the same as a value to an edit field and it will be visible as usual. This can be used as.
return render_to_response('main_template.html', {
'htmlblock': content,
}, context_instance = RequestContext(request))
You can further use the same in edit field as:
<textarea value={{htmlblock}}>
Or render the same normally in
<div id="content">{{htmlblock}}</div>
I'm new to Flask and
I'm trying to create a Stumbleupon like website but I'm having problems while loading the content into an iFrame. I just cant figure it out how to iterate through each url and load them into the iFrame while clicking in the <a> tag.
Here is what I've done:
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def index():
urls = [
'http://www.w3schools.com',
'http://techcrunch.com/',
'https://www.fayerwayer.com/',
]
return render_template('index.html', urls=urls)
if __name__ == "__main__":
app.run(debug=True)
templates/layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="/static/css/normalize.css"/>
<link rel="stylesheet" type="text/css" href="/static/css/foundation.css"/>
</head>
<body>
<nav class="top-bar">
<h3 align="center">Stumble</h3>
</nav>
{% block content %}
{% endblock content %}
</body>
</html>
templates/index.html
{% extends 'layout.html' %}
{% block content %}
<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="????????" frameborder="0"></iframe>
{% endblock content %}
After adding import random at the top of your app.py file you could structure your code like this:
def index():
urls = [
'http://www.w3schools.com',
'http://techcrunch.com/',
'https://www.fayerwayer.com/',
]
iframe = random.choice(urls)
return render_template('index.html', iframe=iframe)
Then access the value in your template:
<iframe frameborder='0' noresize='noresize' style='position: absolute; background: transparent; width: 100%; height:100%;' src="{{ iframe }}" frameborder="0"></iframe>
And simply set the Stumble button to refresh the page.
<h3 align="center">Stumble</h3>
This will be pretty basic, but it will have the behaviour you're describing.
An improvement will be to use the session object to make sure that two subsequent requests do not display the same page inside the iframe.
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>
I am attempting to set up django view for my web application which redirects the page once a file upload is complete, and the status bar showing the upload progress reaches 100%. I have looked around online and attempted to do this in several ways but nothing seems to be working. When I use
render(request, 'template_name')
The application simply returns the plain text of 'template_name' to the console rather than rendering it in the browser window. The original page of the loading bar stays in place after this plain text is returned.
My view looks like the following
def barUpdate(request):
importid = request.GET.get('impid')
response_data = {}
import_status_dict = get_import_status(importid)
status_id = import_status_dict['returnval']
import_status_info = import_status_dict['data_row']
import_status_info = import_status_info[0]
total_rows = import_status_info['total_data_rows']
rows_analyzed = import_status_info['number_of_rows_analyised']
if status_id != 2:
if (rows_analyzed != None and total_rows != None):
percent_complete = int((float(rows_analyzed)/total_rows)*100)
response_data['value'] = percent_complete
if 'percent_complete' in locals():
if response_data['value'] >= 100:
#return render(request,'statustool/completed.html',{'importid':importid,'username':username,'failedparameters':new_failed_param_group,'failedsources':failed_sources,'failedparametergroups':failed_parameters_group,'failedsitegroups':failed_sites_group,'sources':get_sources(), 'failedunits':failed_units})
#Right here I would like to render a new template in my browser, although this is just a dummy template I created for testing
return render(request,'statustool/test.html')
response = HttpResponse(json.dumps(response_data), content_type="application/json")
return response
else:
response_data['value'] = 0
response = HttpResponse(json.dumps(response_data), content_type="application/json")
return response
My dummy template is the following which contains no variables to be passed in from the view
<html>
<head>
test
</head>
<body>
<h1>Finished with data insert!</h1>
</body>
</html>
Is there something I am missing?
If it helps, the current page with the status bar looks like the following and uses a javascript function called status to make GET requests every second to find the upload status for the status bar
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>CACW: Status - Processing</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<!-- Le styles -->
<link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet">
<link href="{{ STATIC_URL }}css/boostrap-responsive.css" rel="stylsheet">
<style>
body,html{
padding-top: 30px; /* 60px to make the container go all the way to the bottom of the topbar */
}
.container{
min-height:100%;
}
.footer{
height:40px;
margin-top:-25px;
}
.barcontainer{
width: 100px;
color: blue;
}
progress {
background-color: whiteSmoke;
border-radius: 2px;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.25) inset;
width: 250px;
height: 20px;
position: relative;
display: block;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/d3examples.js"></script>
<script type="text/javascript">
var importNum = {{importid}}
function status(){
var barProgress = window.setInterval("getProgress(importNum);", 1000);
}
var url=api_server_address+"import/status/update/";
var getProgress = function(importid) {
$.ajax({
url: "https://cacw.luc.edu/status/update/",
data: { impid: importid },
type: "GET",
dataType: "json"
})
.done(function(data){
$('#progressBar').val(data['value']);
console.log(data);
});
}
</script>
</head>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">CACW</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active">Home</li>
<li>Wiki</li>
<li>Contact</li>
</ul>
<a class="btn btn-primary pull-right" href="/logout">Logout</a>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<body onload="status({{importid}});">
<div class="container">
<div class="page-header">
<p><h2>Import {{ importid }} Status.</h2></p>
{{percent_complete}}
<progress id="progressBar" value={{status}} max="100"></progress>
</div>
</div>
<div class="footer">
<div class="navbar-fixed-bottom">
<hr>
<div class = "container" style="text-align: center">
<p> Help - Information - Contact - Wiki <p>
<img src="{{ STATIC_URL }}img/luc_logo.jpg"></img>
</div>
</div>
</div>
</body>
</html>
Since you are just getting the data in an AJAX call, this will never update your page (from the server side). What you can do is add a flag/object/parameter to your servers response to indicate when the upload is done, then on the client side, redirect to that location when the upload is finished.
Server side:
# code shortened a bit... continues from after line defining percent complete
response_data['value'] = percent_complete if 'percent_complete' in locals() else 0
response_data['done'] = response_data['value'] >= 100
return HttpResponse(json.dumps(response_data), content_type="application/json")
Client Side:
var getProgress = function(importid) {
$.ajax({
url: "https://cacw.luc.edu/status/update/",
data: { impid: importid },
type: "GET",
dataType: "json"
})
.done(function(data) {
if(data['done']) {
// I forget if this is how to do a redirect but it's where you put it
location.href('whatever/your/url/is');
} else {
$('#progressBar').val(data['value']);
console.log(data);
}
});
}