11๐
โ
If you have the function read_file
in your views.py
adjust your urls.py
to:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^test/$', views.read_file, name='test'),
url(r'^impala/$', views.people, name='impala'),
]
Fix your function based view:
from django.http import HttpResponse
def read_file(request):
f = open('path/text.txt', 'r')
file_content = f.read()
f.close()
return HttpResponse(file_content, content_type="text/plain")
Spin up up your development server and visit localhost:port/test
. You should see the content of test.txt
.
If you want to pass the content of the text file to your template.html
add it to the context
variable and access it in your template with {{ file_content }}
.
def read_file(request):
f = open('path/text.txt', 'r')
file_content = f.read()
f.close()
context = {'file_content': file_content}
return render(request, "index.html", context)
Keep in mind that a web server like nginx
or apache
would normally take care of serving static files for performance reasons.
๐คYannic Hamann
0๐
you can pass content of your file as a string to your html template
def read_file(request):
f = open('path/text.txt', 'r')
file_contents = f.read()
f.close()
args = {'result' : file_contents }
return render(request, "index.html", context, args)
#######################index.html
<HTML>
...
<BODY>
<P>{{ result }} </p>
</BODY>
</HTML>
๐คSecane
Source:stackexchange.com