Display contents of a text file in Django template - python

I am attempting to create a file in simple website and then read the contents of the same in a variable inside a Django view function and parse the variable to the template to be displayed on web page.
However, when I print the variable, it appears the same on cmd as is in the original text file, but the output on the web page has no formattings but appears like a single string.
I've been stuck on it for two days.
Also I'm relatively new to django and self learning it
file1 = open(r'status.txt','w',encoding='UTF-8')
file1.seek(0)
for i in range(0,len(data.split())):
file1.write(data.split()[i] + " ")
if i%5==0 and i!=0 and i!=5:
file1.write("\n")
file1.close()
file1 = open(r'status.txt',"r+",encoding='UTF-8')
d = file1.read()
print(d) #prints on cmd in the same formatting as in text file
return render(request,'status.html',{'dat':d}) **#the html displays it only as a single text
string**
<body>
{% block content %}
{{dat}}
{% endblock %}
</body>

Use the linebreaks filter in your template. It will render \n as <br/>.
use it like -:
{{ dat | linebreaks }}
from the docs:
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (<br>) and a new line followed by a
blank line becomes a paragraph break (</p>).
You can use linebreaksbr if you don't want <p> tag.

It's because in HTML newline is </br> in Python it is \n. You should convert it, before rendering
mytext = "<br />".join(mytext.split("\n"))

Depending of your needs and the file format you want to print, you may also want to check the <pre> HTML tag.

Related

How to pass value from python to html form using flask/jinja

So I first create an array of all folders in a specific directory, I then pass that to my html file.
def test_yt_vid():
mylist = os.listdir(WD+r"static/"+YOUTUBE_FOLDER)
full_path = (WD+YOUTUBE_FOLDER)
return dict(mylist=mylist, full_path=full_path)
Next I look through that array to find what file has been selected.
<select name=list id="videolist" method="GET" action="/">
{% for mylist in mylist %}
<option value= "{{mylist}}" SELECTED>{{mylist}}</option>"
{% endfor %}
</select>
Next I use JS to get the specific value into a variable
$('#videolist').change(function () {
//console.log($("#videolist").val());
var fileInput = $("#videolist").val())};
So The problem is here, I'm not sure how I would go about passing that value into the following jinja code
<video id="videotesting1" class="video" width="300" height="240" autoplay loop controls="true">
<source src="{{url_for('static',filename='videoTest/' + 'testVid.mp4')}}" type="video/mp4">
</video >
I'm trying to replace 'testVid.mp4' with the variable fileInput from the JS, I tried using $("#videotesting1").attr("src","{{url_for('static',filename='videoTest/'" + fileInput +")}}");'
But no luck so far.
This is different to "How do you change video src using jQuery?" because I am trying to pass a jinja variable to HTML using js.
You have some wrong closed quotes. Take a look at filename, where you set 'videoTest/' plus some variable value (e.g x), which results in 'videoTest/'x. Do you notice it? The single quote closed after videoTest should appear after the variable fileInput. The correct way would be:
$("#videotesting1").attr("src","{{url_for('static',filename='videoTest/" + fileInput + "')}}");
When you modify the src, has by inspect element the src changed, but the desired video isn't being played? If so, try:
$("#videotesting1").load()
Take a look at what load does # JQuery docs.
Figure out the problem, the file name has to go outside the jinja code because it doesnt get rendered by jinja for some reason when the event happens.
$("#videotesting1").attr("src","{{url_for('static',filename='videoTest/')}}" + fileInput);

Multiline posting in HTML

I'm totally new at web development and I am currently trying to create a little website. The goal of this site, is to show random quotes of some of my teachers. The main pages are actually working just fine (I can get random quotes of my whole database, and random quotes from every teacher). But, I wanted to show all the quotes on the same page, and it happens they just appear all on the same line... And it's quite embarrassing...
In my python code, I used "\n" between each quote, so each new one started on a new line. But, on my HTML code, when I pass this string, it seems to have no effect I all the quotes just follow themselves on one line....
I'm using a Flask application, and a python class:
for i in range(2, max):
inte = inte + citation.ClasseCitations('Classe/citations.json','Classe/profs.json', prof, i).corps + ' \n '
return render_template("integrale.html", citation=inte, auteur=prof)
In my HTML file, I use citation like this:
<p>{{ citation }}</p>
Try this :
for i in range(2, max):
inte = inte + citation.ClasseCitations('Classe/citations.json','Classe/profs.json', prof, i).corps + ' <br/> '
return render_template("integrale.html", citation=inte, auteur=prof)
I'm not able to comment, but try it with
<br/>
instead of
\n
this could work.
I'd try using a list object within your flask-app.
Then in your html:
{% for quote in quotes %}
{{quote}} <br>
{% endfor %}
More on jinja2's for-loops
http://jinja.pocoo.org/docs/2.9/templates/#for-loop

Problems with displaying the content of a text file in a tpl using the bottle framwork

Im trying to display the content of a text file in a template without any luck so far. This is
my code so far:
#route('/show_article/<filename>')
def show_article(filename):
stat_art=static_file(filename, root="articles")
return template('show_article', stat_art=stat_art)
And this is the paragraph in my template to display the content of the file
<p>
{{stat_art}}
</p>
I know that I could just return the static_file() but I will need to design the page with
some css and stuff later.
Thanks in advance and sorry for if my english is not correct!
You've misunderstood what static_file does.
Luckily, the fix is simple: just read the file yourself and pass its contents to the template, like so:
#route('/show_article/<filename>')
def show_article(filename):
with open(filename) as f: # <-- you'll need the correct path here, possibly including "articles"
stat_art = f.read()
return template('show_article', stat_art=stat_art)
That should do the trick.
[Btw, nice first question!]

python script to convert " into a html tag

I would like to add two html tags to this file. Each line ends with <br> which is done via something like
>>> f = open("/tmp/x","r")
>>> con = f.readlines()
>>> for line in con:
... print line + "<br>"
...
Now I would like to replace " with specific html tag <h3>. For ex, I have file with content
This is test file named "file.txt" and below is the way to
understand its data and values etc
This is line "one" is also "tricky" to change
expected output is :
This is test file named <h3>file.txt</h3> and below is the way to <br>
understand its data and values etc<br>
This is line <h3>one</h3> is also <h3>tricky</h3> to change <br>
I'm thinking about have two flags for appearance of " . If its odd then use <h3> else use </h3> something like that.If you anyother solution , please suggest.
With import re at the top of your code,
line = re.sub(r'"([^"]*)"', r'<h3>\1</h3>', line)
should do the substitutions you show in your examples.
This doesn't catch an "extra/odd/spare" occurrence of ", only pairs of "s -- if you need to do some other substitution to the "odd" double-quote if any, that's easily arranged as a next step of processing for line.

Programmatically delete everything before a HTML node?

I am trying to create a corpus of data from a set of .html pages I have stored in a directory.
These HTML pages have lots of info I don't need.
This info is all stored before the line
<div class="channel">
How can I programmatically remove all of the text before
<div class="channel">
in every HTML file in a folder?
Bonus question for a 50point bounty :
How do I programmatically remove everything AFTER, for example,
<div class="footer">
?
So if my index.html was previously :
<head>
<title>This is bad HTML</title>
</head>
<body>
<h1> Remove me</h1>
<div class="channel">
<h1> This is the good data, keep me</h1>
<p> Keep this text </p>
</div>
<div class="footer">
<h1> Remove me, I am pointless</h1>
</div>
</body>
After my script runs, I want it to be :
<div class="channel">
<h1> This is the good data, keep me</h1>
<p> Keep this text </p>
</div>
This is a bit heavy on memory usage, but it works. Basically you open up the directory, get all ".html" files, read them into a variable, find the split point, store the before or after in a variable, and then overwrite the file.
There are probably better ways to do this, nonetheless, but it works.
import os
dir = os.listdir(".")
files = []
for file in dir:
if file[-5:] == '.html':
files.insert(0, file)
for fileName in files:
file = open(fileName)
content = file.read()
file.close()
loc = content.find('<div class="channel">')
newContent = content[loc:]
file = open(fileName, 'w')
file.write(newContent)
file.close()
If you wanted to just keep up to a point:
newContent = content[0:loc - 1] # I think the -1 is needed, not sure
Note that the things you're searching should be kept in a variable, and not hardcoded.
Also, this won't work recursively for file/folder structures, but you can find out how to modify it to do that very easily.
to remove everything above and everything below
that means the only thing left should be this section:
<div class="channel">
<h1> This is the good data, keep me</h1>
<p> Keep this text </p>
</div>
rather than thinking to remove the unwanted, it would be easier to just extract the wanted.
you can easily extract channel div using XML parser such as DOM
You've not mentioned a language in the question - the post is tagged with python so this answer might still be out of context, but I'll give a php solution that could likely easily be rewritten in another language.
$html='....'; // your page
$search='<div class="channel">';
$components = explode($search,$html); // [0 => before the string, 1 => after the string]
$result = $search.$components[1];
return $result;
To do the reverse is fairly easy too; simply take the value of $components[0] after altering $search to your <div class="footer"> value.
If you happen to have the $search string cropping up multiple times:
$html='....'; // your page
$search='<div class="channel">';
$components = explode($search,$html); // [0 => before the string, 1 => after the string]
unset($components[0]);
$result = $search.implode($search,$components);
return $result;
Someone who knows python better than I do feel free to rewrite and take the answer!

Categories