Reputation: 16469
I'm trying to get started on a simple project to display a bit of HTML. However when I run my code I cannot seem to locate the html file. I am following what the tutorial on the Django website says
"Within the templates directory you have just created, create another directory called polls, and within that create a file called index.html. In other words, your template should be at polls/templates/polls/index.html. Because of how the app_directories template loader works as described above, you can refer to this template within Django simply as polls/index.html."
SO I put my index.html into
homepage/templates/homepage/index.html
I have not yet added anything to my models.py
proj urls.py:
from django.conf.urls import include, url, patterns
urlpatterns = patterns('',
url(r'homepage/',include('homepage.urls', namespace = "homepage")),
)
app urls.py
from django.conf.urls import patterns, url
from homepage import views
urlpatterns = patterns('',
url(r'^$', views.index, name = 'index'),
)
views.py:
from django.http import HttpResponse
from django.template import RequestContext, loader
def index(request):
template = loader.get_template('homepage/index.html')
return HttpResponse(template)
)
******UPDATE************
So with a bit of tinkering I seem to be able to grab the HTML file. However, the display of this HTML file is not behaving correctly. For instance, if I were to have this bit:
<!DOCTYPE html>
<html>
<body>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
</body>
</html>
The output would be a blank page. The page source would display:
<Text Node: '<!DOCTYPE html>
<html>
<b'>
Not sure why it is behaving this way. Would it have to do withi my having django-pipeline installed and also twitter bootstrap?
Upvotes: 0
Views: 109
Reputation: 15854
The problem is with return HttpResponse(template)
. The HttpResponse
accepts content
for it's first argument. The content could be anything that has a string representation (implements either __str__
or __unicode__
, depending on passing Content-Encoding
header to the response and it's charset) or is iterable. In the latter case, all elements yield by it have to representable by a string.
The issue you are experiencing is that you are passing a Template
object to the response, which is iterable (implements __iter__
method). Iterating the template yields all the compiled nodes. The nodes themselves implement __repr__
which is used when __str__
is missing. And the HttpResponse
, if content
is iterable, returns all elements that are yield from iterating the iterable.
You can simulate this:
from django.http import HttpResponse
from django.template import RequestContext, loader
def index(request):
template = loader.get_template('homepage/index.html')
for n in template:
print n
return HttpResponse(template)
Upvotes: 1